nth-of-type表现得像n-child

baa*_*roz 2 html css css-selectors css3

我有这个HTML代码:

 <div class="productWarp">
    <div class="clear"></div>
    <div class="productLine" ></div>
    <div class="clear"></div>
    <div class="productLine" ></div>
    </div>
Run Code Online (Sandbox Code Playgroud)

CSS:

  .productWarp .productLine {
        background-color: #DFDDDD;
        border-bottom: 1px solid #B7B7B7;
        padding-right: 5px;
    }


    .productWarp .productLine:nth-of-type(2)
    {
        background-color: white;
        border-bottom: 1px solid #B7B7B7;
        padding-right: 5px;
    }
Run Code Online (Sandbox Code Playgroud)

这选择了productWarp的第二个子项(第一个productLine)而不是第二个productLine,所以它正确地表现为nth-child选择器

<div class="productWarp">
    <div class="clear"></div>
    <div class="productLine" ></div>//this one is choose
    <div class="clear"></div>
    <div class="productLine" ></div>//this one should be choose
    </div>
Run Code Online (Sandbox Code Playgroud)

知道这里有什么不对吗?

Bol*_*ock 6

:nth-of-type()查看元素的类型,而不是类.在这种情况下,所有元素都是类型div,这就是为什么:nth-of-type()工作完全相同的原因:nth-child().

如果您只有两个.productLine元素,请使用以下选择器来设置第二个元素的样式:

.productWarp .productLine ~ .productLine
{
    background-color: white;
    border-bottom: 1px solid #B7B7B7;
    padding-right: 5px;
}
Run Code Online (Sandbox Code Playgroud)

否则,您只需通过:nth-child()索引(在这种情况下:nth-child(4))或.productLine通过添加更多重复该~ .productLine部件的规则来覆盖后续元素的样式.