跳至主要內容

Sass嵌套

刘春龙原创...大约 1 分钟WEB前端Sass教程文档

css中重复写选择器是非常恼人的。如果要写一大串指向页面中同一块的样式时,往往需要 一遍又一遍地写同一个ID

<div id="content">
    <article>
        <h1>标题</h1>
        <p>文字</p>
    </article>
    <aside></aside>
</div>
#content article h1 { color: #333 }
#content article p { margin-bottom: 1.4em }
#content aside { background-color: #EEE }

像这种情况,sass可以让你只写一遍,且使样式可读性更高。在Sass中,你可以像俄罗斯套娃那样在规则块中嵌套规则块。sass在输出css时会帮你把这些嵌套规则处理好,避免你的重复书写。

#content {
    article {
        h1 { color: #333; }
        p { margin-bottom: 1.4em; }
    }
    aside { background-color: #EEE; }
}

大多数情况下这种简单的嵌套都没问题,但是有些场景下不行,比如你想要在嵌套的选择器 里边立刻应用一个类似于:hover的伪类。为了解决这种以及其他情况,sass提供了一个特殊结构 &

article a {
    color: blue;
    &:hover { color: red }
}
效果展示
<div id="content">
    <article>
        <h1>标题</h1>
        <p>文字</p>
    </article>
    <aside></aside>
</div>
#content {
    article {
        h1 { color: #333; }
        p { 
            margin-bottom: 1.4em; 
            &:hover { color:red }
        }
    }
    aside { background-color: #EEE; }
}

轻松一刻 🎧

音乐
音乐

视频教程 🎥

至此,本章节的学习就到此结束了,如有疑惑,可对接技术客服open in new window进行相关咨询。

上次编辑于:
贡献者: 刘春龙
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.7