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
?
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)
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.
+ 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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With