css nesting

CSS, Modern CSS, Nesting

Write nested CSS rules directly in native CSS without preprocessors.

Explanation

  • & represents the parent selector, allowing you to reference it within nested rules.
  • & hover, & focus: Creates pseudo-class selectors for the parent element.
  • & .child: Selects elements with class child inside the parent.
  • Native CSS nesting eliminates the need for Sass/Less preprocessors in many cases.

Usage

To write nested CSS rules natively:

.button {
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  background: #007bff;
  color: white;
  cursor: pointer;

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

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

  & .icon {
    margin-right: 8px;
  }

  &.primary {
    background: #28a745;
  }

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