阿里云主机折上折
  • 微信号
Current Site:Index > Native nesting rules

Native nesting rules

Author:Chuan Chen 阅读数:35492人阅读 分类: CSS

Native Nesting Rules

CSS native nesting rules allow developers to write styles for one selector inside another selector. This structured approach makes the code easier to maintain and understand. Nesting reduces repetitive code, resulting in more concise stylesheets.

Basic Syntax

Native nesting uses syntax similar to Sass/Less but is implemented directly in native CSS. The basic structure places child selectors within the curly braces of the parent selector:

.parent {
  color: red;
  
  .child {
    font-size: 16px;
  }
}

This compiles to:

.parent {
  color: red;
}

.parent .child {
  font-size: 16px;
}

Nesting Combinators

Nesting supports all CSS combinators, including descendant, child, adjacent sibling, and general sibling selectors:

/* Descendant selector */
nav {
  ul {
    margin: 0;
  }
}

/* Child selector */
article {
  > p {
    line-height: 1.5;
  }
}

/* Adjacent sibling selector */
h2 {
  + p {
    margin-top: 0;
  }
}

/* General sibling selector */
h3 {
  ~ p {
    color: #666;
  }
}

Usage of the & Symbol

The & symbol represents the parent selector and is particularly useful for concatenating or modifying the parent selector:

.button {
  &-primary {
    background: blue;
  }
  
  &:hover {
    opacity: 0.8;
  }
  
  .dark-theme & {
    color: white;
  }
}

This compiles to:

.button-primary {
  background: blue;
}

.button:hover {
  opacity: 0.8;
}

.dark-theme .button {
  color: white;
}

Nested Media Queries

Media queries can also be nested within rules, making responsive design more modular:

.container {
  width: 100%;
  
  @media (min-width: 768px) {
    width: 750px;
  }
  
  @media (min-width: 992px) {
    width: 970px;
  }
}

Nested @-Rules

In addition to media queries, other @-rules like @supports and @keyframes can also be nested:

.element {
  @supports (display: grid) {
    display: grid;
  }
  
  animation: fade 2s;
  
  @keyframes fade {
    from { opacity: 0; }
    to { opacity: 1; }
  }
}

Nested Pseudo-Classes and Pseudo-Elements

Nesting pseudo-classes and pseudo-elements makes the code more intuitive:

.list-item {
  padding: 10px;
  
  &:first-child {
    padding-top: 20px;
  }
  
  &:last-child {
    padding-bottom: 20px;
  }
  
  &::before {
    content: "•";
    margin-right: 5px;
  }
}

Complex Nesting Example

Combining multiple nesting methods to create complex structures:

.card {
  border: 1px solid #ddd;
  border-radius: 4px;
  
  &-header {
    padding: 15px;
    border-bottom: 1px solid #eee;
    
    h3 {
      margin: 0;
    }
  }
  
  &-body {
    padding: 15px;
    
    p {
      &:first-of-type {
        margin-top: 0;
      }
      
      &:last-of-type {
        margin-bottom: 0;
      }
    }
  }
  
  @media (min-width: 768px) {
    display: flex;
    
    &-header {
      flex: 0 0 200px;
      border-bottom: none;
      border-right: 1px solid #eee;
    }
  }
}

Variables in Nesting

CSS variables can also be used within nested structures:

:root {
  --primary-color: #4285f4;
}

.button {
  --button-padding: 10px 15px;
  
  padding: var(--button-padding);
  
  &-primary {
    background: var(--primary-color);
  }
}

Limitations of Nesting

While nesting is powerful, keep in mind:

  1. Excessive nesting can lead to overly specific selectors, impacting performance
  2. Deep nesting reduces code readability
  3. Some complex selectors may not be expressible through nesting
/* Selectors that cannot be directly expressed with nesting */
a:not(.disabled) {
  color: blue;
}

Nesting and BEM Methodology

Nesting can be combined with naming methodologies like BEM:

.block {
  &__element {
    color: red;
    
    &--modifier {
      font-weight: bold;
    }
  }
}

This compiles to:

.block__element {
  color: red;
}

.block__element--modifier {
  font-weight: bold;
}

Browser Compatibility

As of 2023, native CSS nesting is supported by modern browsers, but older versions may require prefixes or polyfills. Support can be checked using @supports:

@supports (selector(&)) {
  /* Styles for browsers that support nesting */
}

@supports not (selector(&)) {
  /* Fallback styles for browsers that don't support nesting */
}

Performance Considerations

Nested CSS selectors perform the same as manually written selectors, but note:

  1. Avoid nesting deeper than 3 levels
  2. Reduce unnecessary nesting levels
  3. Keep selectors concise for high-frequency interactive elements
/* Not recommended */
.page {
  .content {
    .widget {
      .title {
        /* Four levels of nesting */
      }
    }
  }
}

/* Recommended */
.page-content-widget-title {
  /* Single class name */
}

Differences Between Native Nesting and CSS Preprocessors

Key differences between native nesting and preprocessors like Sass/Less:

  1. Native nesting is parsed directly by browsers, no compilation needed
  2. Slight syntax differences, such as requiring & to represent the parent selector
  3. Some advanced preprocessor features may not be supported
/* Sass allows omitting & */
.menu {
  item { /* Invalid in native CSS */
    color: red;
  }
}

/* Native CSS must be written as */
.menu {
  & item {
    color: red;
  }
}

Practical Use Cases

Nesting is particularly suitable for:

  1. Style encapsulation in component-based development
  2. UI structures with clear parent-child relationships
  3. Cases requiring frequent use of parent selector variants
/* Component example */
.alert {
  padding: 15px;
  border-radius: 4px;
  
  &-success {
    background: #dff0d8;
    border: 1px solid #d6e9c6;
  }
  
  &-danger {
    background: #f2dede;
    border: 1px solid #ebccd1;
  }
  
  &-close {
    float: right;
    cursor: pointer;
  }
}

Nesting and CSS Scoping

Nesting can simulate a degree of style scoping but does not provide true style isolation:

.tabs {
  .tab {
    /* Only affects .tab within .tabs */
  }
}

/* Unlike */
.tab {
  /* Affects all .tab elements */
}

Nesting and CSS Custom Properties

CSS variables in nested structures inherit properties:

.component {
  --text-color: #333;
  
  .child {
    color: var(--text-color);
    
    &.dark {
      --text-color: #fff;
    }
  }
}

Debugging Nested Styles

Browser developer tools now support displaying nested structures directly. When debugging:

  1. Inspect the final generated selector
  2. Verify nesting levels are correct
  3. Check specificity calculations
/* Debugging example */
.widget {
  .title {
    /* Displayed as .widget .title in developer tools */
  }
}

Nesting and CSS Modularity

Nesting promotes a modular CSS writing style, where each component can contain its own complete style structure:

/* User card module */
.user-card {
  display: flex;
  
  &-avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
  }
  
  &-info {
    margin-left: 15px;
    
    &-name {
      font-weight: bold;
    }
    
    &-title {
      color: #666;
    }
  }
}

Migrating Existing Code to Nesting

When migrating existing CSS to nesting syntax, it's recommended to:

  1. Refactor gradually, not all at once
  2. Maintain selector specificity
  3. Ensure the final generated selectors match the original
/* Original CSS */
.sidebar .menu li.active > a {}

/* Nested version */
.sidebar {
  .menu {
    li {
      &.active {
        > a {}
      }
    }
  }
}

Nesting and CSS Frameworks

When using CSS frameworks, nesting can better encapsulate override styles:

.bootstrap-overrides {
  .btn {
    border-radius: 0;
    
    &.btn-primary {
      background: var(--brand-color);
    }
  }
}

Nesting vs. CSS-in-JS

Compared to CSS-in-JS solutions, native nesting:

  1. Does not require a JavaScript runtime
  2. Offers better performance
  3. Lacks true style isolation and dynamic capabilities
/* Native nesting */
.component {
  .item {
    color: red;
  }
}

/* CSS-in-JS equivalent */
const styles = {
  item: {
    color: 'red'
  }
}

Nesting Best Practices

  1. Limit nesting depth (recommended no more than 3 levels)
  2. Use meaningful names
  3. Avoid over-reliance on nesting to create specificity
  4. Combine with CSS custom properties
  5. Keep flat structure options for complex components
/* Recommended approach */
.modal {
  &-header, &-body, &-footer {
    padding: 15px;
  }
  
  &-header {
    border-bottom: 1px solid #eee;
  }
}

/* Not recommended */
.modal {
  .modal-header {
    .modal-header-inner {
      .modal-header-title {
        /* Excessive nesting */
      }
    }
  }
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:作用域样式

下一篇:容器查询

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.