Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Target element only if it doesn't have any subsequent siblings [duplicate]

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?

like image 661
marchello Avatar asked Oct 29 '22 22:10

marchello


1 Answers

: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>
like image 151
Juan Ferreras Avatar answered Nov 30 '22 09:11

Juan Ferreras