簡體   English   中英

css甚至不使用偽元素

[英]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>

而我的css:

.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM