CSS:第n个样式的兄弟姐妹 [英] CSS: style nth sibling
问题描述
是否可以在纯CSS中设置第n个兄弟的样式?
例如,当鼠标悬停在第1个.child
上时,我们可以设置第4个或第5个.child
的样式吗?
Is it possible to style the nth sibling in pure CSS?
For example, can we style 4-th or 5-th .child
when hover on 1-st .child
?
<div class="parent">
<div class="child"> 1 </div>
<div class="child"> 2 </div>
<div class="child"> 3 </div>
<div class="child"> 4 </div>
<div class="child"> 5 </div>
</div>
更新我想我的问题有点不正确.不好意思.
update I guess my question was not correct a bit. Excuse me for that.
我的意思是,我可以为徘徊在其上的.child的第n个同胞设置样式吗?
I meant can I style nth sibling of a .child that I hovered on?
即当鼠标悬停在1st .child
上时,样式为4th .child
;当鼠标悬停在第二个等时,样式为第五个.child
.
I.e. style 4-th .child
when hover on 1-st .child
; style 5-th .child
when hover on 2-nd, etc.
推荐答案
可以.您将常规兄弟选择器(〜)与:hover
.
.child:first-of-type:hover ~ .child:nth-of-type(4) {
color: red;
}
<div class="parent">
<div class="child"> 1 </div>
<div class="child"> 2 </div>
<div class="child"> 3 </div>
<div class="child"> 4 </div>
<div class="child"> 5 </div>
</div>
〜组合器分隔两个选择器,并且仅在第二个选择器位于第一个选择器之后且与第二个选择器匹配并且都共享一个公共父项时.
The ~ combinator separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent.
更新
更新我想我的问题有点不正确.不好意思.
update I guess my question was not correct a bit. Excuse me for that.
我的意思是我可以为第n个悬停的.child兄弟姐妹设置样式吗?
不,因为据我所知,无法计数兄弟姐妹".
您可以解决该问题,比如说您要在悬停时突出显示每个.child
的第二个兄弟姐妹.
No, since as far as I know there's no way for "counting siblings".
You could work-around the problem, say you want to highlight the second sibling of each .child
when hovering.
.child:nth-of-type(1):hover ~ .child:nth-of-type(3) {
color: red;
}
.child:nth-of-type(2):hover ~ .child:nth-of-type(4) {
color: red;
}
.child:nth-of-type(3):hover ~ .child:nth-of-type(5) {
color: red;
}
.child:nth-of-type(4):hover ~ .child:nth-of-type(6) {
color: red;
}
.child:nth-of-type(5):hover ~ .child:nth-of-type(7) {
color: red;
}
<div class="parent">
<div class="child"> 1 </div>
<div class="child"> 2 </div>
<div class="child"> 3 </div>
<div class="child"> 4 </div>
<div class="child"> 5 </div>
</div>
为简化此任务,您可能需要使用SASS之类的预处理器:
To simplify this task, you may want to use a preprocessor like SASS:
@each $i in (1, 2, 3, 4, 5) {
.child:nth-of-type(#{$i}):hover ~ .child:nth-of-type(#{$i + 2}) {
color: red;
}
}
将在CSS之上生成.
这篇关于CSS:第n个样式的兄弟姐妹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!