Selector for one tag directly followed by another tag

CssCss Selectors

Css Problem Overview


This selects all <B> tags directly preceded by <A> tags:

A+B {
    /* styling */
}
    

What is the selector for all <A> tags directly followed by <B> tags?

Here's sample HTML fitting my question:

<a>some text</a>
<b>some text</b>

Css Solutions


Solution 1 - Css

Do you mean to style A given that it has a B element directly inside or followed? Like this:

<A>
    <B>
    </B>
</A>

// OR

<A>
</A>
<B>
</B>

You can't do such a thing in CSS (yet). Eric Meyer states that this kind of selector has been discussed quite a few times on the CSS mailing list, and isn’t doable. Dave Hyatt, one of the core WebKit developers, comments with a good explanation of why it can’t be done.

Check out: Shaun Inman's blog post and the comment by Eric Meyer.
David Hyatt weighs in, too.

Solution 2 - Css

You can’t in css.

Edit: To be a bit more helpful, if you use for example jQuery (a JavaScript library), you can use .prev().

Solution 3 - Css

Solution 4 - Css

Although it's not very handy, nowadays you could achieve this behavior by reversing the order of your elements both when you generate the HTML and by applying the CSS rules: display: flex and flex-direction: column-reverse

ul {
  display: flex;
  flex-direction: column-reverse;
}

.b ~ .a {
  color: red;
}

<ul>
    <li class="a">A 3</li>
    <li class="c">C 2</li>
    <li class="c">C 1</li>
    <li class="b">B 1</li>
    <li class="a">A 2</li>
    <li class="a">A 1</li>
</ul>

Also, if you have 2 or more inline elements, you could achieve it by applying float: right, as they will be displayed in reverse order:

ul {
  float: left;
  list-style-type: none;
}

li {
  float: right;
}

li:not(:first-child) {
  margin-right: 20px;
}

.b ~ .a {
  color: red;
}

<ul>
    <li class="a">A 3</li>
    <li class="c">C 2</li>
    <li class="c">C 1</li>
    <li class="b">B 1</li>
    <li class="a">A 2</li>
    <li class="a">A 1</li>
</ul>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMostafa FarghalyView Question on Stackoverflow
Solution 1 - CssNick PrestaView Answer on Stackoverflow
Solution 2 - CssjeroenView Answer on Stackoverflow
Solution 3 - CssMarco MarsalaView Answer on Stackoverflow
Solution 4 - CssMihai MateiView Answer on Stackoverflow