Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite of adjacent sibling selector?

Please check this fiddle - http://jsfiddle.net/vfMsS/. I need to write selectors which select the element after the "active" element and the element before it. The "before" part doesn't seem to work. How to select the element before the a.active?

like image 258
barakuda28 Avatar asked Mar 16 '13 13:03

barakuda28


People also ask

What are the four types of selectors?

Simple selectors (select elements based on name, id, class) Combinator selectors (select elements based on a specific relationship between them) Pseudo-class selectors (select elements based on a certain state) Pseudo-elements selectors (select and style a part of an element)

What is the difference between adjacent sibling selector and general sibling selector?

The adjacent sibling selector is different from the general sibling selector as it selects only the element that immediately follows an element, whereas the general sibling selector selects any element that follows an element.

What is the difference between '+' and '~' sibling selectors?

+ will only select the first element that is immediately preceded by the former selector. ~ selector all the sibling preceded by the former selector. Save this answer.


2 Answers

Like BoltClock said, there is no way to due this in current day browsers. However, I believe it is possible in CSS.

The CSS Selectors level 4 syntax (specifically see this) with the syntax E! + F for "An element E preceding an element F".

So in your case the syntax would be a! + a.active meaning "An element with tag a preceding an element with tag a and class active". As of today, this is not yet implemented in any layout engine

like image 106
Benjamin Gruenbaum Avatar answered Oct 23 '22 10:10

Benjamin Gruenbaum


The adjacent sibling selector only looks forward, not backward. There is no - combinator for previous adjacent siblings.

If you simply need to select anything that isn't .active in the same parent, and you don't mind slightly reduced browser support, you can use :not() instead. If you need to specify a different style for the one that comes after .active, you need to override:

a:not(.active) { background:red }
a.active + a { background:yellow }

Again, this assumes they always share the same parent.

jsFiddle preview

like image 31
BoltClock Avatar answered Oct 23 '22 10:10

BoltClock