[英]css odd even not working with pseudo-elements
我有一個容器div名稱wrapper
,它有幾個名為thumb
子div我想用偶數和奇數應用css pseudo elements
。
<div class="wrapper">
<div class="col-half">
<div class="thumb">
...
</div>
</div>
<div class="col-half">
<div class="thumb">
...
</div>
</div>
<div class="col-half">
<div class="thumb">
...
</div>
</div>
<div class="col-half">
<div class="thumb">
...
</div>
</div>
</div>
.wrapper:nth-child(even) .thumb:after{
//some codes
}
.wrapper:nth-child(odd) .thumb:after{
//some codes
}
但我只得到odd
風格。
由於基於兄弟索引應用odd
和偶數關系,因此需要將其應用於col-half
因為這是重復元素。
由於您的thumb
元素是其父元素的第一個子元素,因此它只滿足odd
選擇器
.wrapper .col-half:nth-child(even) .thumb:after { content: 'x' } .wrapper .col-half:nth-child(odd) .thumb:after { content: 'y' }
<div class="wrapper"> <div class="col-half"> <div class="thumb"> ... </div> </div> <div class="col-half"> <div class="thumb"> ... </div> </div> <div class="col-half"> <div class="thumb"> ... </div> </div> <div class="col-half"> <div class="thumb"> ... </div> </div> </div>
你有一個誤解:nth-child因為它不能作為“這個容器的第n個孩子”,而是“我是我父母的第n個孩子嗎?”。
所以你需要申請:nth-child(odd/even)
到.col-half
:
.col-half:nth-child(even) .thumb:after{
//some codes
}
.col-half:nth-child(odd) .thumb:after{
//some codes
}
這個選擇器的名稱確實引起了許多誤解,因為它太容易誤解你的方式。
.col-half:nth-child(even) {
color: green;
}
.col-half:nth-child(odd) {
color: red;
}
試試這樣: 演示
在你的CSS中,你使用父div顯示偶數和奇數。 相反,你需要使用奇數/偶數重復的子元素
.col-half:nth-child(even) .thumb{
background:#ccc;
}
.col-half:nth-child(odd) .thumb{
background:#f00;
}
試試這一個
.wrapper .col-half:nth-child(2n) .thumb:after {
content: '';
}
.wrapper .col-half:nth-child(2n-1) .thumb:after {
content: '';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.