我有一个正常的代码
<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;
<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;
为什么?我试图添加像这样的div.h2.item-title:nth-of-type(4),但它没有帮助。
答案 0 :(得分:0)
这是因为:nth-
是相对于父母计算的。因为你将最后一个元素包装到div,它变成:first-child
答案 1 :(得分:0)
这是因为nth-of-type仅适用于兄弟元素。如果你想访问最后一个元素,现在你必须给 编辑抱歉我的坏h2是一个元素所以只需使用此
div>h2.item-title:nth-of-type(1)