nth-of-type表现不尽如人意

时间:2014-05-30 16:16:57

标签: html css

HTML

<div id="content">          
    <div id="ok" class="content-block warning"><div></div><span>&#10003 Everything is OK!</span> </div>         
    <div id="module_1" class="content-block small">asfdasdf</div>
    <div id="module_2" class="content-block small">asdfasdf</div>
    <div id="module_3" class="content-block small">asfasdf</div>
    <div id="module_4" class="content-block small">asdfasdf</div>
    <div id="module_5" class="content-block small">asfasdf</div>
    <div id="module_6" class="content-block small">asdfasdf</div>
    <div id="module_7" class="content-block big"></div> 
    <div id="module_8" class="content-block big"></div>     
</div>

CSS

.small:nth-of-type(1) {
    background-color: black;
    border-style: solid;
    border-width: 15px;
    border-color: black;
}

.small:nth-of-type(2) {
    background-color: red;
}

在此示例中:http://jsfiddle.net/CNBsY/2/我无法弄清楚为什么nth-of-type(1)nth-of-type(2)选择我想要选择的第一件事时没有选择任何内容。有人理解为什么会这样吗?

3 个答案:

答案 0 :(得分:3)

那是因为它是nth-of-type,而不是nth-of-class

HTML中的第一个div没有small类,因此没有与.smallnth-of-type(1)匹配的元素。

答案 1 :(得分:1)

伪选择器:nth-of-type()选择类型的标记

在您的示例中,它是div。当您在类(.small:nth-of-type(1))上设置选择器时,只有当第一个div具有该类而不是这种情况时,才会使用css。

答案 2 :(得分:1)

试试这个:

HTML

<div id="content">          
    <span id="ok" class="content-block warning">&#10003 Everything is OK!</span>
    <ul>         
        <li id="module_1" class="content-block small">asfdasdf</li>
        <li id="module_2" class="content-block small">asdfasdf</li>
        <li id="module_3" class="content-block small">asfasdf</li>
        <li id="module_4" class="content-block small">asdfasdf</li>
        <li id="module_5" class="content-block small">asfasdf</li>
        <li id="module_6" class="content-block small">asdfasdf</li>
        <li id="module_7" class="content-block big"></li> 
        <li id="module_8" class="content-block big"></li>
    </ul>    
</div>

CSS

li:nth-of-type(1) {
    background-color: black;
    border-style: solid;
    border-width: 15px;
    border-color: black;
}

li:nth-of-type(2) {
    background-color: red;
}

这是一个更好的语义。

相关问题