Ralph David Abernathy - 10 months ago 54
Sass (Sass) Question

# CSS selector: How to select element sibling AND element itself?

So I have a set of links, and want to apply a style [let's say

color: red;
] to those links only if they are siblings in the DOM. For example, if I have three links:

<a class="nav-link-primary">link</a>
<a class="nav-link-secondary">link</a>
<a class="nav-link-tertiary">link</a>


They should all be red.

But if I have something like this:

<a class="nav-link-primary">link</a>
<span>Lorem</span>
<a class="nav-link-secondary">link</a>
<a class="nav-link-tertiary">link</a>


Then only the last two links should be red, as they are siblings. Is it possible to do this with CSS?

Here is what I've tried

.nav-link-primary ~ .nav-link-primary,
.nav-link-primary ~ .nav-link-secondary,
.nav-link-primary ~ .nav-link-tertiary,
.nav-link-secondary ~ .nav-link-primary,
.nav-link-secondary ~ .nav-link-secondary,
.nav-link-secondary ~ .nav-link-tertiary,
.nav-link-tertiary ~ .nav-link-primary,
.nav-link-tertiary ~ .nav-link-secondary,
.nav-link-tertiary ~ .nav-link-tertiary {
color: red;
}

.nav-link-primary:first-child + .nav-link-secondary{
color: red;
}

.nav-link-secondary:first-child + .nav-link-primary{
color: red;
}

<a class="nav-link-primary">link</a>
<a class="nav-link-secondary">link</a>
<a class="nav-link-tertiary">link</a>

Here is my CodePen link: http://codepen.io/obliviga/pen/jryPgO

This does not make the first link red, even though it has a sibling defined in the first block of selectors. Any ideas?

Answer Source

The first link isn't red because there's no preceding element to refer to, and there isn't a CSS selector that can do this. See Is there a "previous sibling" CSS selector?. A better idea would be to have a common parent element to refer to, such as .adjacent-links, like so:

.adjacent-links a { color: red; }
<a class="nav-link-primary">link</a>
<span>Lorem</span>
<span class="adjacent-links">
<a class="nav-link-secondary">link</a>
<a class="nav-link-tertiary">link</a>
</span>