在CSS3中,我们有很多选择器能够赋予DEV的生产力,有助于优化DOM和类别的使用。
1.儿童组合者(>)
CSS3子组合器选择器由大于符号(>)表示,并仅用于选择父元素的直接子元素。大于符号的左侧的选择器代表父元素,而右侧的选择器表示直接的子元素。
在下面的代码中,我们的需求p
和h2
在div
内部应具有特定的样式,而不是section
中的那些。
<div>
<h2>Iron Man</h2>
<p>ron Man is a superhero appearing in American comic books published by Marvel Comics. The character was co-created by writer and editor Stan Lee</p>
<a href="#">Read more...</a>
<h2>Super Man</h2>
<p>Clark Joseph Kent, best known by his superhero persona Superman, is a superhero in the DC Extended Universe series of films, based on the DC Comics character </p>
<a href="#">Read more...</a>
<section>
<h2>Collection</h2>
<h4>all years collections is in $</h4>
<a href="#">Read more...</a>
<p>The most valuable copy of this issue ever sold was a NM/M 9.8 sold in 2019 for $1,575.</p>
</section>
</div>
现在,如果您会使用
div p { color: #999; }
div h2 { color: #848484; }
这将适用于所有p
,H2
以及该部分内部的样式(这不是要求)。那么,我们该如何实现呢?
答案是儿童组合者(更大的标志>)。它将选择父母的所有直接孩子。
div > p {
color: #999;
}
div > h2 {
color: #898989;
}
在这里,它将仅在h2
和p
上实现样式,它们是div
的直接子,而不是section
。
2。相邻的兄弟姐妹选择器(+)
CSS中的相邻选择器是一个选择器,它选择与另一元素相邻的元素(即,在此之后)。相邻的选择器由加号(+)表示,并用于选择立即遵循指定元素的第一个元素。
eg:所有的a
之后是p
样式都将获得实施(颜色:红色,边框:点缀)。但是,在收集部分中,a
标签将无法实现该样式,因为介于两者之间。
<div>
<h2>Iron Man</h2>
<p>ron Man is a superhero appearing in American comic books published by Marvel Comics. The character was co-created by writer and editor Stan Lee</p>
<a href="#">Read more...</a>
<h2>Super Man</h2>
<p>Clark Joseph Kent, best known by his superhero persona Superman, is a superhero in the DC Extended Universe series of films, based on the DC Comics character </p>
<a href="#">Read more...</a>
<section>
<h2>Collection</h2>
<p>The most valuable copy of this issue ever sold was a NM/M 9.8 sold in 2019 for $1,575.</p>
<h4>all years collections is in $</h4>
<a href="#">Read more...</a>
</section>
</div>
div > h2 {
color: blue;
}
p + a {
color: red;
border:1px dotted #ccc;
padding: 2px;
}
3。一般兄弟姐妹选择器(〜)
CSS中的一般同级选择器由Tilde符号(〜)表示,并用于选择第一个元素(左侧的选择器)和共享同一父元素之后的所有同级元素。
在这方面,只要标签是同一父母的孩子,这些标签将在样式中实现。
在这里所有的a
标签,然后是p
标签将标签样式(颜色:红色,边框:点点)。无论收集部分之间都有另一个元素。
<div>
<h2>Iron Man</h2>
<p>ron Man is a superhero appearing in American comic books published by Marvel Comics. The character was co-created by writer and editor Stan Lee</p>
<a href="#">Read more...</a>
<h2>Super Man</h2>
<p>Clark Joseph Kent, best known by his superhero persona Superman, is a superhero in the DC Extended Universe series of films, based on the DC Comics character </p>
<a href="#">Read more...</a>
<section>
<h2>Collection</h2>
<p>The most valuable copy of this issue ever sold was a NM/M 9.8 sold in 2019 for $1,575.</p>
<h4>all years collections is in $</h4>
<a href="#">Read more...</a>
</section>
</div>
div > h2 {
color: blue;
}
p ~ a {
color: red;
border:1px dotted #ccc;
padding: 2px;
}
快乐学习!