简体   繁体   English

css甚至不使用伪元素

[英]css odd even not working with pseudo-elements

I have a container div names wrapper and it has several child divs named thumb I want to apply css pseudo elements with the even and odd. 我有一个容器div名称wrapper ,它有几个名为thumb子div我想用偶数和奇数应用css pseudo elements

My codes are 我的代码是

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

And my css: 而我的css:

.wrapper:nth-child(even) .thumb:after{
    //some codes
}
.wrapper:nth-child(odd) .thumb:after{
    //some codes
}

But i am getting only odd styles. 但我只得到odd风格。

Since the odd and even relationship is applied based on sibling index, you need to apply it on col-half as that is the repeated element. 由于基于兄弟索引应用odd和偶数关系,因此需要将其应用于col-half因为这是重复元素。

Since your thumb element is the first child of its parent, it will only satisfy the odd selector 由于您的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> 

You have a misunderstanding about :nth-child as it does not work as "nth child of this container" but as "am I the nth child of my parent?". 你有一个误解:nth-​​child因为它不能作为“这个容器的第n个孩子”,而是“我是我父母的第n个孩子吗?”。

So you need to apply :nth-child(odd/even) to .col-half : 所以你需要申请:nth-child(odd/even).col-half

.col-half:nth-child(even) .thumb:after{
    //some codes
}
.col-half:nth-child(odd) .thumb:after{
    //some codes
}

The name for this selector has really caused many misunderstandings as it is too easy to misunderstand the way you did. 这个选择器的名称确实引起了许多误解,因为它太容易误解你的方式。

.col-half:nth-child(even) {
    color: green;
}
.col-half:nth-child(odd) {
    color: red;
}

Try like this: Demo 试试这样: 演示

In your css, You are using the parent div for showing even and odd. 在你的CSS中,你使用父div显示偶数和奇数。 Instead you need to use odd / even for child elements which repeats 相反,你需要使用奇数/偶数重复的子元素

.col-half:nth-child(even) .thumb{
  background:#ccc;
}
.col-half:nth-child(odd) .thumb{
   background:#f00;
}

Try This One 试试这一个

.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