HTML and CSS course ยท Module 9: Modern CSS

CSS Nesting - Native Style Nesting

14 min read ยท
In this lesson4

In plain CSS you start every rule for the inside of a card with the same selector: .card h2, .card p, .card .button. You repeat it like a scribe copying the same heading onto every scroll, and when you rename the class, you have to fix every place. For years only Sass solved this. CSS Nesting is a native CSS feature that allows nesting selectors inside other selectors, similar to preprocessors like Sass or Less, without any compilation. This significantly improves the readability and organization of code, and since 2023 it has worked in all major browsers.

CSS Nesting Basics

Simple Nesting

Let's start with a comparison. We wrote the same card styles first in the traditional way and then with nesting:

/* Traditional CSS */
.card {
  padding: 1rem;
  background: white;
  border-radius: 8px;
}

.card h2 {
  font-size: 1.5rem;
  margin-bottom: 1rem;
  color: #333;
}

.card p {
  line-height: 1.6;
  color: #666;
}

.card .button {
  padding: 0.5rem 1rem;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
}

/* CSS Nesting */
.card {
  padding: 1rem;
  background: white;
  border-radius: 8px;

  h2 {
    font-size: 1.5rem;
    margin-bottom: 1rem;
    color: #333;
  }

  p {
    line-height: 1.6;
    color: #666;
  }

  .button {
    padding: 0.5rem 1rem;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
  }
}

Both versions give an identical result. The nested h2 means exactly .card h2, a heading inside the card, and has the same specificity. Only the notation changes: the name .card appears once, and everything related to the card sits in one block.

Using the & Symbol

The & symbol represents the parent selector and allows creating more complex selectors, such as states, variants and pseudo-elements:

.button {
  padding: 0.75rem 1.5rem;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;

  /* Hover and focus states */
  &:hover {
    background: #0056b3;
    transform: translateY(-1px);
  }

  &:focus {
    outline: none;
    box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.25);
  }

  &:active {
    transform: translateY(0);
  }

  /* Button variants */
  &.secondary {
    background: #6c757d;

    &:hover {
      background: #545b62;
    }
  }

  &.danger {
    background: #dc3545;

    &:hover {
      background: #c82333;
    }
  }

  /* State modifiers */
  &.loading {
    position: relative;
    color: transparent;

    &::after {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      width: 16px;
      height: 16px;
      border: 2px solid #ffffff;
      border-top: 2px solid transparent;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      transform: translate(-50%, -50%);
    }
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;

    &:hover {
      background: #007bff;
      transform: none;
    }
  }
}

@keyframes spin {
  0% { transform: translate(-50%, -50%) rotate(0deg); }
  100% { transform: translate(-50%, -50%) rotate(360deg); }
}

&:hover without a space is the same button in its hover state, and &.secondary is a button that also has the secondary class. Watch out for the space: & :hover would mean any descendant of the button under the cursor. There is also an important difference from Sass: in native CSS you cannot glue a class name together with &__title, that works only in a preprocessor.

Advanced Nesting Techniques

Combinators and Pseudo-selectors

You can nest everything: descendant selectors, pseudo-classes, combinators and even media queries. Here is a whole navigation with a dropdown menu in one block:

.navigation {
  display: flex;
  align-items: center;
  padding: 1rem 2rem;
  background: #ffffff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);

  .logo {
    font-size: 1.5rem;
    font-weight: bold;
    color: #007bff;
    text-decoration: none;

    &:hover {
      color: #0056b3;
    }
  }

  .nav-list {
    display: flex;
    list-style: none;
    margin: 0 0 0 auto;
    padding: 0;
    gap: 2rem;

    .nav-item {
      position: relative;

      .nav-link {
        display: block;
        padding: 0.5rem 0;
        color: #333;
        text-decoration: none;
        font-weight: 500;
        transition: color 0.3s ease;

        &:hover {
          color: #007bff;
        }

        &.active {
          color: #007bff;

          &::after {
            content: '';
            position: absolute;
            bottom: -8px;
            left: 0;
            right: 0;
            height: 2px;
            background: #007bff;
          }
        }
      }

      /* Dropdown menu */
      .dropdown {
        position: absolute;
        top: 100%;
        left: 0;
        min-width: 200px;
        background: white;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        opacity: 0;
        visibility: hidden;
        transform: translateY(-10px);
        transition: all 0.3s ease;
        z-index: 1000;

        .dropdown-item {
          .dropdown-link {
            display: block;
            padding: 0.75rem 1rem;
            color: #333;
            text-decoration: none;

            &:hover {
              background: #f8f9fa;
              color: #007bff;
            }

            &:first-child {
              border-radius: 8px 8px 0 0;
            }

            &:last-child {
              border-radius: 0 0 8px 8px;
            }
          }
        }
      }

      /* Show dropdown on hover */
      &:hover .dropdown {
        opacity: 1;
        visibility: visible;
        transform: translateY(0);
      }
    }
  }

  /* Responsive navigation */
  .mobile-toggle {
    display: none;
    flex-direction: column;
    gap: 4px;
    background: none;
    border: none;
    cursor: pointer;

    .bar {
      width: 25px;
      height: 3px;
      background: #333;
      transition: all 0.3s ease;
    }

    &.active {
      .bar:nth-child(1) {
        transform: rotate(45deg) translate(5px, 5px);
      }

      .bar:nth-child(2) {
        opacity: 0;
      }

      .bar:nth-child(3) {
        transform: rotate(-45deg) translate(7px, -6px);
      }
    }
  }

  @media (max-width: 768px) {
    .nav-list {
      position: fixed;
      top: 70px;
      left: 0;
      right: 0;
      flex-direction: column;
      background: white;
      padding: 1rem 2rem;
      transform: translateY(-100%);
      transition: transform 0.3s ease;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);

      &.active {
        transform: translateY(0);
      }

      .nav-item {
        .dropdown {
          position: static;
          opacity: 1;
          visibility: visible;
          transform: none;
          box-shadow: none;
          background: #f8f9fa;
          margin-top: 0.5rem;
        }
      }
    }

    .mobile-toggle {
      display: flex;
    }
  }
}

The &:hover .dropdown rule shows the menu when the cursor is over a list item. Notice the depth, though: .dropdown-link sits six levels down, so the resulting selector has the specificity of six classes and is hard to override. This is an example of what the best practices below will teach you to avoid.

Nesting with Media Queries

A media query nested inside a rule applies to that very rule. Declarations written directly inside @media go to the parent selector:

.hero-section {
  display: flex;
  align-items: center;
  min-height: 100vh;
  padding: 2rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;

  .hero-content {
    max-width: 1200px;
    margin: 0 auto;
    text-align: center;

    .hero-title {
      font-size: 3.5rem;
      font-weight: 700;
      margin-bottom: 1.5rem;
      line-height: 1.2;

      @media (max-width: 768px) {
        font-size: 2.5rem;
      }

      @media (max-width: 480px) {
        font-size: 2rem;
      }
    }

    .hero-subtitle {
      font-size: 1.5rem;
      font-weight: 300;
      margin-bottom: 2rem;
      opacity: 0.9;

      @media (max-width: 768px) {
        font-size: 1.25rem;
      }

      @media (max-width: 480px) {
        font-size: 1.1rem;
      }
    }

    .hero-buttons {
      display: flex;
      gap: 1rem;
      justify-content: center;
      flex-wrap: wrap;

      @media (max-width: 480px) {
        flex-direction: column;
        align-items: center;
      }

      .btn-primary {
        padding: 1rem 2rem;
        font-size: 1.1rem;
        background: rgba(255, 255, 255, 0.2);
        border: 2px solid white;
        color: white;
        border-radius: 50px;
        text-decoration: none;
        transition: all 0.3s ease;
        backdrop-filter: blur(10px);

        &:hover {
          background: white;
          color: #667eea;
          transform: translateY(-2px);
          box-shadow: 0 8px 25px rgba(0,0,0,0.2);
        }

        @media (max-width: 480px) {
          width: 200px;
        }
      }

      .btn-secondary {
        padding: 1rem 2rem;
        font-size: 1.1rem;
        background: transparent;
        border: 2px solid rgba(255, 255, 255, 0.5);
        color: white;
        border-radius: 50px;
        text-decoration: none;
        transition: all 0.3s ease;

        &:hover {
          border-color: white;
          background: rgba(255, 255, 255, 0.1);
        }

        @media (max-width: 480px) {
          width: 200px;
        }
      }
    }
  }

  @media (max-width: 768px) {
    padding: 1rem;
    min-height: 80vh;
  }
}

The title and subtitle shrink at 768px and 480px, and the last media query changes the spacing of the section itself. Every breakpoint stands next to the style it modifies, so you do not have to scroll to a separate @media block at the end of the file.

Nesting @container

You nest the Container Queries from the previous lesson the same way. Let's recall the order: a container with container-type and an optional name, the @container query, styles for the children, a test at different widths:

.card-wrapper {
  container: card / inline-size;
}

.card-title {
  font-size: 1.25rem;

  @container card (min-width: 400px) {
    font-size: 5cqw;
  }
}

When the card container is at least 400px wide, the title gets 5cqw, which is 5% of the container's width. The other units work analogously: cqh measures the height, and cqi and cqb the inline and block dimensions.

Practical Nesting Examples

Complex Form

In a large component, nesting shows the structure like a plan of chambers. The whole contact form, with its fields, states and buttons, fits in a single rule:

.contact-form {
  max-width: 600px;
  margin: 2rem auto;
  padding: 2rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 25px rgba(0,0,0,0.1);

  .form-header {
    text-align: center;
    margin-bottom: 2rem;

    h2 {
      font-size: 2rem;
      color: #333;
      margin-bottom: 0.5rem;
    }

    p {
      color: #666;
      font-size: 1.1rem;
    }
  }

  .form-row {
    display: flex;
    gap: 1rem;
    margin-bottom: 1.5rem;

    @media (max-width: 600px) {
      flex-direction: column;
    }

    .form-group {
      flex: 1;

      &.full-width {
        flex-basis: 100%;
      }
    }
  }

  .form-group {
    margin-bottom: 1.5rem;

    label {
      display: block;
      margin-bottom: 0.5rem;
      font-weight: 600;
      color: #333;

      .required {
        color: #e74c3c;
        margin-left: 0.25rem;
      }
    }

    input, textarea, select {
      width: 100%;
      padding: 0.75rem;
      border: 2px solid #e1e5e9;
      border-radius: 8px;
      font-size: 1rem;
      transition: all 0.3s ease;
      background: #fafbfc;

      &:focus {
        outline: none;
        border-color: #007bff;
        background: white;
        box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
      }

      &::placeholder {
        color: #adb5bd;
      }

      &.error {
        border-color: #e74c3c;
        background: #fff5f5;

        &:focus {
          box-shadow: 0 0 0 3px rgba(231, 76, 60, 0.1);
        }
      }

      &.success {
        border-color: #28a745;
        background: #f8fff9;

        &:focus {
          box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.1);
        }
      }
    }

    textarea {
      min-height: 120px;
      resize: vertical;
    }

    select {
      cursor: pointer;
      background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
      background-position: right 0.5rem center;
      background-repeat: no-repeat;
      background-size: 1.5em 1.5em;
      padding-right: 2.5rem;
    }

    .error-message {
      display: block;
      margin-top: 0.5rem;
      color: #e74c3c;
      font-size: 0.875rem;
    }

    .help-text {
      display: block;
      margin-top: 0.5rem;
      color: #6c757d;
      font-size: 0.875rem;
    }
  }

  .checkbox-group {
    margin: 1.5rem 0;

    .checkbox-item {
      display: flex;
      align-items: center;
      gap: 0.75rem;
      margin-bottom: 1rem;

      input[type="checkbox"] {
        width: auto;
        margin: 0;

        &:checked + label::before {
          background-color: #007bff;
          border-color: #007bff;
        }
      }

      label {
        margin: 0;
        cursor: pointer;
        user-select: none;

        a {
          color: #007bff;
          text-decoration: none;

          &:hover {
            text-decoration: underline;
          }
        }
      }
    }
  }

  .form-actions {
    display: flex;
    gap: 1rem;
    justify-content: flex-end;
    margin-top: 2rem;

    @media (max-width: 480px) {
      flex-direction: column;
    }

    .btn {
      padding: 0.75rem 2rem;
      border: none;
      border-radius: 8px;
      font-size: 1rem;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s ease;
      text-decoration: none;
      display: inline-block;
      text-align: center;

      &.btn-primary {
        background: #007bff;
        color: white;

        &:hover:not(:disabled) {
          background: #0056b3;
          transform: translateY(-1px);
        }

        &:disabled {
          opacity: 0.6;
          cursor: not-allowed;
        }
      }

      &.btn-secondary {
        background: #f8f9fa;
        color: #6c757d;
        border: 1px solid #dee2e6;

        &:hover {
          background: #e9ecef;
          color: #495057;
        }
      }

      @media (max-width: 480px) {
        width: 100%;
      }
    }
  }

  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.9);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12px;

    .spinner {
      width: 40px;
      height: 40px;
      border: 4px solid #f3f3f3;
      border-top: 4px solid #007bff;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
  }
}

The input, textarea, select list gets shared styles, while &:focus, &::placeholder and &.error describe their states. The &:checked + label::before notation shows that after & you can use any combinator, here the adjacent sibling.

Card Component with Variants

Variants and states of a component are a natural place for &. Notice the rule in which & stands at the end of the selector:

.card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  position: relative;

  /* Shadow variants */
  &.shadow-sm {
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  }

  &.shadow-md {
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
  }

  &.shadow-lg {
    box-shadow: 0 10px 25px rgba(0,0,0,0.15);
  }

  /* Interactive variants */
  &.hoverable {
    cursor: pointer;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 12px 30px rgba(0,0,0,0.2);
    }
  }

  &.clickable {
    cursor: pointer;
    user-select: none;

    &:active {
      transform: scale(0.98);
    }
  }

  /* Card components */
  .card-header {
    padding: 1.5rem;
    border-bottom: 1px solid #f0f0f0;

    &.with-image {
      padding: 0;
      position: relative;

      .header-image {
        width: 100%;
        height: 200px;
        object-fit: cover;
      }

      .header-content {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 1.5rem;
        background: linear-gradient(transparent, rgba(0,0,0,0.7));
        color: white;
      }
    }

    .card-title {
      font-size: 1.5rem;
      font-weight: 600;
      margin: 0 0 0.5rem 0;
      color: #333;

      .card-header.with-image & {
        color: white;
      }
    }

    .card-subtitle {
      font-size: 1rem;
      color: #666;
      margin: 0;

      .card-header.with-image & {
        color: rgba(255,255,255,0.9);
      }
    }
  }

  .card-body {
    padding: 1.5rem;

    .card-text {
      line-height: 1.6;
      color: #555;
      margin-bottom: 1rem;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .card-meta {
      display: flex;
      align-items: center;
      gap: 1rem;
      margin-bottom: 1rem;
      font-size: 0.9rem;
      color: #666;

      .meta-item {
        display: flex;
        align-items: center;
        gap: 0.25rem;

        .icon {
          width: 16px;
          height: 16px;
        }
      }
    }

    .card-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 0.5rem;
      margin-bottom: 1rem;

      .tag {
        padding: 0.25rem 0.75rem;
        background: #f8f9fa;
        color: #495057;
        border-radius: 20px;
        font-size: 0.8rem;
        font-weight: 500;

        &.primary {
          background: #e3f2fd;
          color: #1976d2;
        }

        &.success {
          background: #e8f5e8;
          color: #2e7d32;
        }

        &.warning {
          background: #fff3e0;
          color: #f57c00;
        }

        &.danger {
          background: #ffebee;
          color: #d32f2f;
        }
      }
    }
  }

  .card-footer {
    padding: 1rem 1.5rem;
    background: #f8f9fa;
    border-top: 1px solid #f0f0f0;

    .card-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 1rem;

      @media (max-width: 480px) {
        flex-direction: column;
        align-items: stretch;
      }

      .action-group {
        display: flex;
        gap: 0.5rem;

        @media (max-width: 480px) {
          justify-content: center;
        }
      }

      .btn {
        padding: 0.5rem 1rem;
        border: none;
        border-radius: 6px;
        font-size: 0.9rem;
        cursor: pointer;
        text-decoration: none;
        transition: all 0.2s ease;

        &.btn-primary {
          background: #007bff;
          color: white;

          &:hover {
            background: #0056b3;
          }
        }

        &.btn-outline {
          background: transparent;
          color: #007bff;
          border: 1px solid #007bff;

          &:hover {
            background: #007bff;
            color: white;
          }
        }

        &.btn-ghost {
          background: transparent;
          color: #6c757d;

          &:hover {
            background: #e9ecef;
            color: #495057;
          }
        }
      }
    }
  }

  /* Special states */
  &.loading {
    pointer-events: none;

    &::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(255,255,255,0.8);
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  &.disabled {
    opacity: 0.6;
    pointer-events: none;
  }
}

.card-header.with-image & means: this title, but only when it is inside a header with an image. So the & symbol does not have to stand at the beginning.

CSS Nesting Best Practices

1. Limit Nesting Depth

Every nesting level is another class in the selector and higher specificity. Compare a sensible depth with an exaggerated one:

/* Good - maximum 3-4 levels */
.header {
  .navigation {
    .nav-item {
      .nav-link {
        /* maximum level */
      }
    }
  }
}

/* Bad - too deep nesting */
.page {
  .content {
    .section {
      .container {
        .row {
          .column {
            .card {
              .header {
                /* too deep! */
              }
            }
          }
        }
      }
    }
  }
}

Three or four levels are the limit. You will enforce the max-nesting-depth rule automatically in the Stylelint lesson.

2. Use Meaningful Selector Names

Short names such as .title or .img are easy to confuse with classes of other components. It is better to prefix them with the component name:

/* Good */
.product-card {
  .product-image {
    /* styles */
  }

  .product-info {
    .product-title { /* styles */ }
    .product-price { /* styles */ }
  }
}

/* Bad */
.card {
  .img {
    /* styles */
  }

  .info {
    .title { /* styles */ }
    .price { /* styles */ }
  }
}

Names with the product- prefix tell you at once where they belong, and they do not collide with other parts of the page.

Keep order inside a single block: first the layout, then the parts of the component, and finally the states and animations, separated by comments:

.modal {
  /* Basic layout styles */
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;

  /* Background and overlay */
  .modal-backdrop {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    backdrop-filter: blur(4px);
  }

  /* Modal content */
  .modal-content {
    position: relative;
    max-width: 500px;
    margin: 5% auto;
    background: white;
    border-radius: 12px;
    overflow: hidden;

    /* Modal components */
    .modal-header {
      /* styles */
    }

    .modal-body {
      /* styles */
    }

    .modal-footer {
      /* styles */
    }
  }

  /* States and animations */
  &.fade-in {
    animation: modalFadeIn 0.3s ease;
  }

  &.fade-out {
    animation: modalFadeOut 0.3s ease;
  }
}

CSS Nesting significantly improves the organization and readability of CSS code, enabling the creation of more intuitive and maintainable stylesheets. The key is to exercise restraint and follow best practices. My advice: in new projects without a preprocessor, use native nesting boldly, but remember the differences from Sass. In the next lesson you will meet Cascade Layers, which put whole groups of styles in order.

Remember: nesting is like descending into the chambers of a pyramid, because a floor or two down is convenient, but whoever goes too deep loses the way.

Code for this lesson: index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>The :has() selector</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>The :has() selector - the parent reacts to its children</h1>
    <article>
        <h2>Pyramid of Cheops</h2>
        <div class="img-placeholder">IMG</div>
        <p>One of the Seven Wonders of the World.</p>
    </article>
    <article>
        <h2>Sphinx</h2>
        <p>Guardian of the pyramids, without an illustration.</p>
    </article>
    <article>
        <h2>Karnak Temple</h2>
        <div class="video-placeholder">VIDEO</div>
        <p>The largest temple complex.</p>
    </article>
</body>
</html>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is native CSS Nesting?

  2. 2. Which container query unit refers to the container's width?

Hands-on tasks in the game

  • Vertical ordering

    Arrange the correct CSS Nesting syntax:

  • Click in order

    Arrange the correct syntax for a nested pseudo-selector in CSS Nesting:

  • Vertical ordering

    Arrange the process of using Container Queries:

  1. QuestionNative CSS Nesting
  2. QuestionContainer Query Units
  3. Put in orderCSS Nesting Syntax
  4. Click in orderBuilding a CSS Nesting Rule with &
  5. Put in orderContainer Queries Configuration

Useful articles