嵌套中的组合器
本文介绍了嵌套中的组合器。
我们将讲解如何在SASS中使用嵌套组合器,并提供示例代码,帮助你一步步理解。
YouTube Video
嵌套中的组合器
在SASS中,你可以根据父子关系简洁地编写CSS选择器,但需要特别注意正确处理如后代选择器和相邻选择器等组合器。
嵌套基础
在SASS中,通过在父选择器内嵌套子选择器,可以清晰简明地表示CSS中的父子关系。
例子:基本嵌套
1.nav {
2 ul {
3 li {
4 color: blue;
5 }
6 }
7}编译后的CSS
1.nav ul li {
2 color: blue;
3}父选择器引用(&)
SASS中的&用于引用当前父选择器。
组合使用组合器和&
通过使用&,可以构建灵活的选择器。
示例
1.card {
2 & > .title {
3 font-weight: bold;
4 }
5 & + .card {
6 margin-top: 20px;
7 }
8}编译后的CSS
1.card > .title {
2 font-weight: bold;
3}
4.card + .card {
5 margin-top: 20px;
6}“&”的简写表示法
在SASS中,当组合器放在选择器的开头时,父选择器会被隐式插入,所以你可以省略“&”符号。
可以省略的情况
例如,当你写“+ .item”时,SASS会在内部将其解释为“& + .item”,并自动生成与父选择器的组合。
示例
1.item {
2 + .item {
3 margin-top: 10px;
4 }
5 &--hover {
6 background-color: red;
7 }
8}编译后的CSS
1.item + .item {
2 margin-top: 10px;
3}
4.item--hover {
5 background-color: red;
6}组合器概述
CSS组合器用于定义选择器之间的关系。以下是主要的组合器类型。
-
后代选择器(空格) 后代选择器选择包含在父元素中的所有后代元素。 例子:
.parent .child -
子选择器(
>) 子选择器只选择直接子元素。 例子:.parent > .child -
相邻选择器(
+) 相邻选择器选择紧随其后的兄弟元素。 例子:.sibling1 + .sibling2 -
通用兄弟选择器(
~) 通用兄弟选择器选择所有后面的同级兄弟元素。 例子:.sibling1 ~ .sibling2
如何在SASS中使用组合器
后代选择器(空格)
在SASS嵌套中,空格后代选择器默认应用。
示例
1.container {
2 .header {
3 .title {
4 font-size: 20px;
5 }
6 }
7}编译后的CSS
1.container .header .title {
2 font-size: 20px;
3}子选择器(>)
如果要使用子选择器,在SASS代码中显式写出>。
示例
1.container {
2 & > .header {
3 & > .title {
4 font-size: 20px;
5 }
6 }
7}编译后的CSS
1.container > .header > .title {
2 font-size: 20px;
3}相邻选择器(+)
要为紧随其后的兄弟元素设置样式,请使用+。
示例
1.item {
2 & + .item {
3 margin-top: 10px;
4 }
5}编译后的CSS
1.item + .item {
2 margin-top: 10px;
3}通用兄弟选择器(~)
要为同一级所有后续兄弟元素设置样式,请使用~。
示例
1.alert {
2 & ~ .alert {
3 border-top: 1px solid red;
4 }
5}编译后的CSS
1.alert ~ .alert {
2 border-top: 1px solid red;
3}嵌套中的伪类与伪元素
在SASS中也可轻松编写伪类和伪元素。
示例
1.button {
2 &:hover {
3 background-color: blue;
4 }
5 &::after {
6 content: '';
7 display: block;
8 }
9}编译后的CSS
1.button:hover {
2 background-color: blue;
3}
4.button::after {
5 content: '';
6 display: block;
7}实际示例
下面是一个结合多个组合器的复杂样式示例。
SASS代码
1.menu {
2 .menu-item {
3 & > .submenu {
4 display: none;
5
6 & > .submenu-item {
7 font-size: 14px;
8 }
9 }
10 & + .menu-item {
11 margin-left: 15px;
12 }
13 }
14}编译后的CSS
1.menu .menu-item > .submenu {
2 display: none;
3}
4.menu .menu-item > .submenu > .submenu-item {
5 font-size: 14px;
6}
7.menu .menu-item + .menu-item {
8 margin-left: 15px;
9}总结
如果你能正确理解SASS中的嵌套和组合器,就能编写更简洁易读的CSS。
您可以在我们的YouTube频道上使用Visual Studio Code跟随上述文章进行学习。 请也查看我们的YouTube频道。