nth-of-type css,如何正确设置它

时间:2016-10-21 09:39:37

标签: html css

我有一个正常的代码



<html><head>

<style type="text/css"> h2.item-title:nth-of-type(2) {
    background:red;
    }

h2.item-title:nth-of-type(4) {
background:purple;
}

</style>
</head>
<body>

<h2 class="item-title" itemprop="name">
<a href="/link/" itemprop="url">
            Link1       </a>
</h2>

<h2 class="item-title" itemprop="name">
<a href="/link/" itemprop="url">
            Link2       </a>
</h2>
<h2 class="item-title" itemprop="name">
<a href="/link/" itemprop="url">
            Link3       </a>
</h2>
<h2 class="item-title" itemprop="name">
<a href="/link/" itemprop="url">
            Link4       </a>
</h2>
</body>
</html>
&#13;
&#13;
&#13; 但是,如果我想在我的上一个&gt; h2&lt;之前添加任何html标记,则此段落的css代码将停止工作

&#13;
&#13;
<html><head>

<style type="text/css"> h2.item-title:nth-of-type(2) {
    background:red;
    }

h2.item-title:nth-of-type(4) {
background:purple;
}

</style>
</head>
<body>

<h2 class="item-title" itemprop="name">
<a href="/link/" itemprop="url">
            Link1       </a>
</h2>

<h2 class="item-title" itemprop="name">
<a href="/link/" itemprop="url">
            Link2       </a>
</h2>
<h2 class="item-title" itemprop="name">
<a href="/link/" itemprop="url">
            Link3       </a>
</h2>
  <div>
<h2 class="item-title" itemprop="name">
<a href="/link/" itemprop="url">
            Link4       </a>
</h2>
</div>
</body>
</html>
&#13;
&#13;
&#13;

为什么?我试图添加像这样的div.h2.item-title:nth-​​of-type(4),但它没有帮助。

2 个答案:

答案 0 :(得分:0)

这是因为:nth-是相对于父母计算的。因为你将最后一个元素包装到div,它变成:first-child

答案 1 :(得分:0)

这是因为nth-of-type仅适用于兄弟元素。如果你想访问最后一个元素,现在你必须给 编辑抱歉我的坏h2是一个元素所以只需使用此

div>h2.item-title:nth-of-type(1)