1

浏览器支持原生嵌套了!

 9 months ago
source link: https://www.haorooms.com/post/css_nesting
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

之前在 LESS、SASS 等预处理器中嵌套写法,现在原生css竟然支持了哈,从chrome112开始支持!下面尝鲜看看语法!

CSS 原生嵌套语法

div {
    & > p {
        color: red;
    }

    &:hover {
        color: yellow;
    }
}

其语法规则大致如下:

parentRule {
  /* parent rule style properties */
  & childRule {
    /* child rule style properties */
  }
}
<div class="g-container">
    <h3 class="g-h3">CSS 
        <span class="g-span">Haorooms</span>
    </h3>
</div>

上面的html这么写没有问题

div {
    border: 1px solid #000;

    .g-h3 {
        color: red;

        .g-span {
            color: blue;
        }
    }
}

假如如下:

div {
    border: 1px solid #000;

    h3 {
        color: red;

        span {
            color: blue;
        }
    }
}

这么写不生效。需要如下写法

div {
    border: 1px solid #000;

    & h3 {
        color: red;

        & span {
            color: blue;
        }
    }
}

在嵌套中使用伪元素和伪类

div {
  /* ... */
  &:hover {
    color: red;
  }

  &:is(.content, footer) {
    padding: 16px;
  }

  &::before {
    content: "";
    /* ... */
  }
}

这个写法和css预处理器一样的。

css支持原生嵌套功能很强大,基本可以替代sass和less,但是注意的是要用class类,纯标签的化,需要 &


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK