Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

浏览器支持原生嵌套了! #426

Open
confidence68 opened this issue Apr 30, 2024 · 0 comments
Open

浏览器支持原生嵌套了! #426

confidence68 opened this issue Apr 30, 2024 · 0 comments

Comments

@confidence68
Copy link
Owner

前言

之前在 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类,纯标签的化,需要 &

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant