jampjamp jampjamp - 1 month ago 5
CSS Question

nth-of-type css, how to setup it properly

I have a code which works correct



<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>




However, if I would like to add any html tag before my last >h2<, css code for this paragraph stops to work



<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>





Why is that? I've tried to add sth like this div.h2.item-title:nth-of-type(4), but it doesn't help.

Answer

This is because of the reason that the nth-of-type works only for the sibling elements. If you want to access the last element, now you have to give EDIT Sorry My Bad h2 is an element so just use this

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