# CSS Nesting

CSS Nesting provides the ability to nest one style rule inside another, with the selector of the child rule being relative to the selector of the parent rule. This feature, long popular in preprocessors like Sass and Less, is now a native CSS standard.

## 1. The Concept

Nesting allows you to group related styles together, mirroring the HTML structure. This improves readability and maintainability.

**Without Nesting:**
```css
.card {
  background: white;
}

.card .title {
  font-weight: bold;
}

.card:hover {
  background: #f0f0f0;
}
```

**With Nesting:**
```css
.card {
  background: white;

  .title {
    font-weight: bold;
  }

  &:hover {
    background: #f0f0f0;
  }
}
```

## 2. The Nesting Selector (`&`)

The `&` symbol represents the parent selector. It is used to chain selectors or apply pseudo-classes.

### Chaining and Pseudo-classes
```css
.button {
  background: blue;

  /* Equivalent to .button:hover */
  &:hover {
    background: darkblue;
  }

  /* Equivalent to .button.primary */
  &.primary {
    background: red;
  }
}
```

## 3. Nesting Media Queries

You can also nest media queries inside a selector. This keeps the responsive styles right next to the base styles.

```css
.container {
  width: 100%;

  @media (min-width: 768px) {
    width: 50%;
  }
}
```

## 4. Gotchas

*   **Specificity:** The specificity of the nested selector is calculated as if it were written out fully (e.g., `.card .title`).
*   **Syntax:** Modern browsers support "relaxed parsing", allowing you to nest elements directly (e.g., `div { p { color: red; } }`). Older implementations required the `&` or `is()` for element selectors.

[[programming/css/css]]
[[programming/css/selectors]]
[[programming/css/specificity]]