Select all elements before element with class?

In CSS, can I select all elements before an element with a given class?

HTML example:

<div>
    <a href>One</a>
    <a href>Two</a>
    <a href>Three</a>
    <a href class="active">Four</a>
    <a href>Five</a>
</div>

And CSS:

.active:(all-before) {
    border-left: solid 1px #C0FFEE;
}

Thus, the links “One”, “Two” and “Three” will have a left border, but “Four” and “Five” will not.

+4
source share
2 answers

a {
  text-decoration: none;
  border-left: 1px solid black;
}

a.active, a.active ~ * {
  border: none;
}
<div>
    <a href>One</a>
    <a href>Two</a>
    <a href>Three</a>
    <a href class="active">Four</a>
    <a href>Five</a>
</div>
Run codeHide result
+4
source

Well, this is usually not possible, but you can hack it in some way.

So, for example, if you want to do this:

.active:(all-before) {
    border-left: solid 1px #C0FFEE;
}

You can do it:

a {
    border-left: solid 1px #C0FFEE;
}
a.active, a.active~a {
    border-left: none;
}

So, you put the style you want in the first selector, and then disable this construct in the second selector.

Working example: http://jsfiddle.net/prrd14u2/

javascript, jquery .

+2

All Articles