I have the following markup and style:
[class^="container"] .target:last-of-type {
color:red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="container-1">
<div class="item">1</div>
<div class="item">2</div>
<div class="target">3</div>
<div class="item">4</div>
<div class="item">5</div>
</div>
<br>
<div class="container-2">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="target">5</div>
</div>
</body>
</html>
I want to select the .target element, but only if it is the last within its container.
The :last-of-type class works in this case, I just don't understand why. Shouldn't it highlight both .target elements? They are the last-of-type (and only) elements within their parent containers. Or I am misunderstanding the :last-of-type selector?
:last-of-type doesn't look for the class, but rather, as the name implies, the type as in the tag of the element.
That's why it's only highlighting the last element on the second container div, it's applying the rule when the .target becomes also the :last-of-type, that is, the last div inside its container.
I've edited your answer, check what it does when it's either .item or the div tag itself before the last-of-type selector.
[class^="container"] .target:last-of-type {
color:blue;
}
[class^="container"] .item:last-of-type {
text-decoration: underline;
}
[class^="container"] div:last-of-type {
text-indent: 20px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="container-1">
<div class="item">1</div>
<div class="item">2</div>
<div class="target">3</div>
<div class="item">4</div>
<div class="item">5</div>
</div>
<br>
<div class="container-2">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="target">5</div>
</div>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With