【问题标题】:nth odd/even child elements h3第 n 个奇/偶子元素 h3
【发布时间】:2015-08-13 18:08:38
【问题描述】:

我有一个这样的 html 页面设置

<div class="row row-venue">
    <div class="col-sm-12">
        <h3>Venue 1</h3>
    </div>
</div>
<div class="row row-venue">
    <div class="col-sm-12">
        <h3>Venue 2</h3>
    </div>
</div>

我要做的就是让每个奇数 h3 与每个偶数颜色不同。我试过下面的代码

div.row-venue div.col-venue h3:nth-of-type(odd){
  color:white;
}
div.row-venue div.col-venue h3:nth-of-type(even){
  color:black;
}

甚至只是尝试过

h3:nth-of-type(odd){
  color:white;
}

h3:nth-of-type(even){
  color:black;
}

我似乎无法理解它,任何帮助将不胜感激

【问题讨论】:

  • 谢谢,现在很有意义,以前从来没有用过,只是用来硬编码,这会节省我很多时间。赞赏

标签: html css css-selectors


【解决方案1】:

&lt;h3&gt; 始终是&lt;div class="col-sm-12"&gt; 的第一个孩子。因为计数是零基数 - 第一个孩子 = 偶数,所以您定义的偶数规则适用于所有 &lt;h3&gt; 元素。

要得到你的要求,你需要找到&lt;div class="row row-venue"&gt; 项之间的第n 个孩子:

.row-venue:nth-child(odd) h3 {
    color: white;
}
.row-venue:nth-child(even) h3 {
    color: black;
}

如果您的 div 与其他元素混合,请使用 :nth-of-type 而不是 :nth-child

【讨论】:

  • OP 使用的是:nth-of-type 而不是:nth-child,不确定澄清的目的。你是不是不小心把这两个翻了?
  • 他说他“甚至只是尝试过” :nth-of-type 作为一种可能的解决方案。
【解决方案2】:

您的 CSS 在 .col-venue 元素中定位奇数/偶数 &lt;h3&gt; 标记,我在您的标记中没有看到。即使.col-venue 在您的标记中,它也只会针对其中的 H3 - example here

您需要在标记中从更高级别控制样式,见下文。

<div class="row row-venue">
    <div class="col-sm-12">
        <h3>Venue 1</h3>
    </div>
</div>
<div class="row row-venue">
    <div class="col-sm-12">
        <h3>Venue 2</h3>
    </div>
</div>
.row-venue:nth-of-type(odd) h3 {
    color: red;
}
.row-venue:nth-of-type(even) h3 {
    color: black;
}

http://jsfiddle.net/Lvezzrnq/

使用上述 CSS 选择器,您可以定位奇数和偶数 .row-venue 元素,然后深入到 h3。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    相关资源
    最近更新 更多