Dancia
Dancia

Reputation: 812

How to target all elements, except last one with css?

.outer a:not(:last-of-type) {
  color: red;
}
<div class="outer">
  <a href="#">First</a>
  <a href="#">Second</a>
  <div>
    <a href="#">Third</a>
  </div>
  <a href="#">Fourth</a>
  <a href="#">Fifth</a>
</div>

Is there a way, to target all <a>'s inside div.outer (I can't think of way to target the one inside ) container? The only workaround I can think of is css: .outer a:not(.last) and adding .last to last <a>. Any ideas? Background: The main idea why I'm doing this, is that I have elements, which line near edge of container, so each of them has to have margin of 10 from right, except last one. In this case, i don't have to type class margin-right-10 in each <a>, its just my own style I'm following.

Upvotes: 3

Views: 3738

Answers (2)

dfsq
dfsq

Reputation: 193301

If you number of levels inside .outer is known (or limited) you can extend selector like this:

.outer > * > a,
.outer > a:not(:last-of-type) {
    color: red;
}
<div class="outer">
  <a href="#">First</a>
  <a href="#">Second</a>
  <div>
    <a href="#">Third</a>
  </div>
  <a href="#">Fourth</a>
  <a href="#">Fifth</a>
</div>

The part .outer > * > a makes sure that deeper links are also included into matched set.

UPD. Version #2 that also takes into consideration situation when the nested links are the last:

.outer > *:not(:last-child) > a,
.outer > a:not(:last-child) {
    color: red;
}
<div class="outer">
  <a href="#">First</a>
  <a href="#">Second</a>
  <div>
    <a href="#">Third</a>
  </div>
  <a href="#">Fourth</a>
  <a href="#">Fifth</a>
  <div>
    <a href="#">Six</a>
  </div>
</div>

Upvotes: 3

Mooseman
Mooseman

Reputation: 18891

.outer > a:not(:last-of-type), .outer > div a

Works as well, but without changing your markup.

Upvotes: 2

Related Questions