I have been searching for the past hour to find the correct CSS Selector (or at least to find out if one exists) to style the elements in the DOM immediately before and after another element.
At the moment, I have a ul whose li elements have a border-bottom property. I would like to change the colour of that border if there is an element immediately after it in the DOM. If possible, I would like to avoid using separate classes for this.
Consider the following markup:
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
<li class="divider">2</li>
<li>List Item 4</li>
<li>etc.</li>
</ul>
I would like to add border-bottom: none to <li>List Item 3</li> and any other li elements that are immediately followed by li.divider.
Is there are a CSS selector for this, something like ul > li, but for this? It doesn’t need to be cross-browser, and can be CSS3; just needs to work on WebKit browsers…
this is not possible. there is no css selector for preceding elements; neither preceding siblings, nor ancestors.
you can, however, apply a style to the next (and only the next) sibling:
you can chain it. this style:
and this (combinable):
allows you to apply just one of either the “predivider” class, or the “divider” class, dependent of the divider being the first element (and thus has none before it) or not.