html - 着色某些类别的交替div

标签 html css css-selectors

我的代码如下:

HTML

<div class="divs">
  <div class="row">row 0</div>
  <div class="not-row"></div>
  <div class="row">row 1</div>
  <div class="not-row"></div>
  <div class="row">row 2</div>
  <div class="not-row"></div>
  <div class="row">row 3</div> 
  <div class="not-row"></div>
</div>

CSS

.row:nth-child(even) {
  background: #fff;
}

.row:nth-child(odd) {
  background: #eee;
}

这应该将其中两行的背景绘制为灰色,将其中两行的背景绘制为白色。不幸的是,它将他们所有的背景都涂成灰色。我做错了什么?

我尝试使用 nth-of-type 而不是 nth-child 但这并没有改变任何东西。

jsFiddle example

最佳答案

甚至只是使用(默认)

.row {}

然后覆盖奇数:

.row:nth-child(4n+1) {}

.row {
    background: #fff;
}
.row:nth-child(4n+1) {
   background: #eee;
}

http://jsfiddle.net/b8ma1hon/3/


更多关于如何nth-child作品可以在这里找到:

https://css-tricks.com/how-nth-child-works/

enter image description here


您不能简单地使用 even/odd在这种情况下,因为它与所有子元素有关,而不仅仅是类 row 的子元素。 .

您包含 .row在选择器中纯粹是一个额外的标准,对 nth-child 没有影响选择器。

同样我可以说:

.row:nth-child(1):hover {}

这会将选择限制为类为 row 的元素,这是第 2 个 child ,目前处于悬停状态。

如果这是所有悬停元素中的第二个元素,那将毫无意义,因为您一次只能将鼠标悬停在一个元素上。

我希望这是有道理的!


还值得注意的是,您的选择器现在依赖于 not-row存在,或者至少存在于 row 之间的某种元素元素。

如果这要改变,那么您的选择器也必须改变。

或者,您可以更改 not-row 的元素类型元素到其他东西,这样你就可以利用 nth-of-type选择器:

<div class="divs">
    <div class="row">row 0</div>
    <span class="not-row"></span>
    <div class="row">row 1</div>
    <span class="not-row"></span>
    <div class="row">row 2</div>
    <span class="not-row"></span>
    <div class="row">row 3</div> 
    <span class="not-row"></span>
</div>

.row {
    background: #fff;
}
.row:nth-of-type(odd) {
   background: #eee;
}

http://jsfiddle.net/b8ma1hon/5/

关于html - 着色某些类别的交替div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31672260/

相关文章:

html - Angular ng 模型表达式

html - 无法在正确的位置获得 wordpress 搜索栏

css - 如何获得流畅的谷歌字体?

javascript - 获取特定元素的 xpath 和 css 选择器的最佳方法

javascript - 提交给 servlet 的隐藏表单字段值不正确

html - 列表元素 "dots"结束于节元素之外

html - 使用 CSS 右对齐表格单元格中的文本

html - div中的自适应iframe

html - 是否有选择器以特定网格位置的元素为目标?

css - 属性选择器: Can't isolate one element from the other