Define styles to elements immediately before and after another element CSS
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>
<开发者_JAVA百科;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:
li.divider + li {border:1px solid black}
you can chain it. this style:
li.predivider {border-bottom: none} /*before*/
li.predivider + li {border:1px solid black} /*divider*/
li.predivider + li + li {border-bottom: none} /*after*/
and this (combinable):
li.divider {border:1px solid black} /*divider*/
li.divider + li {border-bottom: none} /*after*/
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.
.divider + li
to select to immidiate sibling <li>
to .divider
.
As for the one before it, I don't think it's possible (please correct me if I'm wrong)
精彩评论