---
name: css-nesting
description: Convert flat CSS to nested & syntax while satisfying stylelint's no-descending-specificity and no-duplicate-selectors rules. Use when nesting selectors, refactoring flat CSS to &, or fixing stylelint specificity/duplicate errors after nesting.
user-invocable: true
title: css-nesting
canonical_url: https://skilld.dev/gh/fubits1/svelte-skills/css-nesting
last_updated: 2026-10-25T14:32:29.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [references/honeycomb-plan.md](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/css-nesting/references/honeycomb-plan.md).
>
> If the user asked to install this Skill, run `npx skilld install fubits1/svelte-skills/css-nesting`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/css-nesting`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/fubits1/svelte-skills/css-nesting) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/css-nesting`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/css-nesting --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/css-nesting --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# CSS Nesting with Stylelint Compliance

Flat-to-nested CSS conversion breaks when done incrementally because each edit shifts specificity ordering, triggering cascading linter errors. This skill prevents that by requiring upfront analysis before any edits.

## When This Applies

- Converting flat CSS selectors to nested `&` syntax
- Fixing `no-descending-specificity` or `no-duplicate-selectors` errors after nesting
- Any CSS restructuring that changes selector source order

## The Two Rules You Must Satisfy

### `no-descending-specificity`

Selectors matching the **same DOM element** must appear in ascending specificity order in source. A `.foo` (0,1,0) appearing after `.bar:hover .foo` (0,3,0) is an error because both can match a `.foo` element.

Selectors matching **different elements** don't conflict regardless of order.

### `no-duplicate-selectors`

Two rule blocks resolving to the same selector are forbidden. Nesting changes resolved selectors: `& .child` inside `.parent` resolves to `.parent .child`. A second `.parent` block is a duplicate even if the contents differ.

Exception: the same selector inside vs outside a `@media` block is allowed (different parent nodes).

## The Workflow

### Step 1: Map the DOM hierarchy

Write out the parent-child nesting from the HTML template:

```css
.container
  .wrapper
    .item
      .label
```

### Step 2: List every selector with its specificity

For each selector in the flat CSS, calculate specificity and note which DOM element it matches:

```css
.wrapper              (0,1,0)  matches .wrapper
.wrapper:hover        (0,2,0)  matches .wrapper
.item                 (0,1,0)  matches .item
.wrapper:hover .item  (0,3,0)  matches .item
.label                (0,1,0)  matches .label
.container:has(:hover) .wrapper:not(:has(:hover))  (0,4,0)  matches .wrapper
```

### Step 3: Group by target element and sort ascending

For each element, the selectors that match it must appear in ascending specificity order in the final source:

```css
Selectors matching .wrapper:
  .wrapper              (0,1,0)  ← first
  .wrapper:hover        (0,2,0)
  .container:has(:hover) .wrapper:not(:has(:hover))  (0,4,0)  ← last

Selectors matching .item:
  .item                 (0,1,0)  ← first
  .wrapper:hover .item  (0,3,0)  ← last
```

### Step 4: Design the block structure

Place blocks so that within each element group, specificity ascends in source order. Key principles:

**Nest children inside parents** to match DOM hierarchy. `& .item` inside `.wrapper` resolves to `.wrapper .item` (0,2,0), this increases specificity vs flat `.item` (0,1,0), which is fine as long as the ordering still ascends.

**High-specificity cross-cutting selectors go last.** If `.container:has(:hover) .wrapper:not(...)` at (0,4,0) matches `.wrapper`, it must appear in source after all other `.wrapper`-matching selectors. Since it's nested under `.container`, put the `.container` block after the `.wrapper` block.

**One block per selector.** Can't have two `.container` blocks, use one block with all its rules.

**`@media` nests inside its parent block.** `@media` inside `.wrapper { }` avoids both duplicate-selector issues and keeps related rules together.

### Step 5: Write the entire `<style>` block in one edit

Never do incremental edits. Write the complete nested CSS as a single replacement. Each incremental edit shifts source order and triggers new linter errors.

### Step 6: Validate

1. Run stylelint on the file
2. Run existing tests
3. If using pixel-perfect workflow, compare before/after measurements

## Specificity Calculation Reference

| Component                                                         | Specificity added                            |
| ----------------------------------------------------------------- | -------------------------------------------- |
| Element type (`div`, `span`)                                      | (0,0,1)                                      |
| Class, attribute, pseudo-class (`.foo`, `:hover`, `:nth-child()`) | (0,1,0)                                      |
| ID (`#bar`)                                                       | (1,0,0)                                      |
| `:is()`, `:not()`, `:has()`                                       | Highest specificity of their argument        |
| `&` (nesting selector)                                            | Same as `:is()`, takes parent's specificity |
| `~`, `+`, `>`, ` ` (combinators)                                  | Add nothing                                  |

Nesting with `&` uses `:is()` wrapping semantics per [CSS Nesting Module Level 1](https://www.w3.org/TR/css-nesting-1/). The `&` selector adopts the highest specificity from the parent selector list.

## Example: The Hard Case

This is the pattern that breaks naive nesting, a high-specificity desaturate rule that crosses parent-child boundaries:

**Problem:** `.container:has(:hover) .child:not(:has(:hover))` at (0,4,0) matches `.child` elements. If `.container` block comes first with this rule inside, then `.child` block comes second at (0,1,0), that's descending specificity.

**Solution:** Put `.child` block first (all its selectors ascending), then `.container` block second (with the desaturate rule at the end). They target different elements so the block ordering doesn't trigger `no-descending-specificity`.

```css
/* .child block first — all .child-matching selectors in ascending order */
.child {
  /* (0,1,0) matches .child */

  & .grandchild {
    /* (0,2,0) matches .grandchild */
  }

  &:hover {
    /* (0,2,0) matches .child */

    & .grandchild {
      /* (0,3,0) matches .grandchild — ascending */
    }
  }

  &:nth-child(2n) {
    /* (0,2,0) matches .child — same specificity as :hover, OK */
  }

  @media (width > 768px) {
    /* desktop overrides — same selectors allowed inside @media */
    &:nth-child(2n) {
      /* different parent node, not a duplicate */
    }
  }
}

/* .container block second — highest-specificity .child selector comes last */
.container {
  /* (0,1,0) matches .container — different element, no conflict */

  @media (width > 768px) {
    /* desktop overrides */
  }

  /* Desaturate — (0,4,0) matches .child — after all .child selectors above */
  &:has(:hover) .child:not(:has(:hover)) {
    opacity: 0.85;

    & .grandchild {
      /* (0,5,0) matches .grandchild — after all .grandchild selectors above */
      filter: grayscale(100%);
    }
  }
}
```

## References

- [CSS Nesting Module Level 1 (W3C)](https://www.w3.org/TR/css-nesting-1/)
- [MDN: CSS Nesting and Specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Nesting/Nesting_and_specificity)
- [stylelint: no-descending-specificity](https://stylelint.io/user-guide/rules/no-descending-specificity/)
- [stylelint: no-duplicate-selectors](https://stylelint.io/user-guide/rules/no-duplicate-selectors/)
- [Honeycomb grid example](https://skilld.dev/api/skills-raw/fubits1/svelte-skills/css-nesting/references/honeycomb-plan.md): worked specificity analysis and solution for a grid with a cross-cutting desaturate rule
