使用具有跨度元素的Nth-Child - 由于某些原因,所有跨度元素都是奇数

时间:2016-03-17 23:43:26

标签: html css

我正在尝试使用nth-child伪选择器来定位包含div中的奇数跨度。我的HTML标记看起来像这样。

<div class="load-data">
<span>Company: Heavy Haul LLC.</span><br> 
<span>Name: John Smith</span><br> 
<span>Phone: (123)-456-7890</span><br> 
<span>Position: Chase</span><br> 
<span>From: Knoxville, TN</span><br> 
<span>To: Nashville, TN</span><br> 
<span>Date: 03/02/2016</span><br> 
<span>Rate: $250 Day Rate</span><br> 
</div>

我的CSS看起来像这样:

.load-data {
 border: 1px solid #454545;
 background-color: #121212;
 display: inline-block;
 margin: 5px 10px;
 text-align: left;
}
.load-data > span {
 padding: 5px;
 display: inline-block;
}
.load-data span:nth-child(even) {
 color: #ff6400;
}
.load-data span:nth-child(odd) {
 color: #ff9900;
}

但由于某种原因,每个span元素的颜色都为ff9900。为什么他们都是奇数?

为了调试我尝试使用nth-child(5)只是为了看看会发生什么,第三行是出于某种原因而不是第五行被选中。

我不明白为什么会这样。

1 个答案:

答案 0 :(得分:2)

选择

  1. 请改用nth-of-type,将其作为孩子计算<br>

  2. 使用nth-child和div而不是span并摆脱<br>

  3. 如果您只是移除<br>并使用nth-child,那么<span>inline后会发生混乱,请参阅第二个示例。

    此时,您可以通过将此分配给您的CSS来更改<span>

    span { display: block; }
    

    或将<span>更改为<div>

    <强>段

    &#13;
    &#13;
    .load-data span:nth-of-type(even) { background: blue; }
    .load-data span:nth-of-type(odd) { background: red; }
    .x span:nth-child(even) { background: blue; }
    .x span:nth-child(odd) { background: red; }
    &#13;
    <div class="load-data">
    <span>Company: Heavy Haul LLC.</span><br> 
    <span>Name: John Smith</span><br> 
    <span>Phone: (123)-456-7890</span><br> 
    <span>Position: Chase</span><br> 
    <span>From: Knoxville, TN</span><br> 
    <span>To: Nashville, TN</span><br> 
    <span>Date: 03/02/2016</span><br> 
    <span>Rate: $250 Day Rate</span><br> 
    </div>
    <br><br>
    <div class="x">
    <span>Company: Heavy Haul LLC.</span>
    <span>Name: John Smith</span>
    <span>Phone: (123)-456-7890</span>
    <span>Position: Chase</span>
    <span>From: Knoxville, TN</span> 
    <span>To: Nashville, TN</span> 
    <span>Date: 03/02/2016</span>
    <span>Rate: $250 Day Rate</span> 
    </div>
    &#13;
    &#13;
    &#13;