Selector for one tag directly followed by another

2019-02-07 16:24发布

问题:

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>

回答1:

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().



回答2:

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.



回答3:

You can ONLY do the converse: This selects all tags directly preceded by tags.

This is logically equivalent to your request.

I often use this to style a row of many checkboxes with labels

CSS:

label+input {
    margin-left: 4px;
}

DOM:

<input id="a" name="a" type="checkbox"/><label for="a">...</label>
<input id="b" name="b" type="checkbox"/><label for="b">...</label>
<input id="c" name="c" type="checkbox"/><label for="c">...</label>


回答4:

You could, but the support is still buggy. The name of that is the adjacent sibling selector

http://reference.sitepoint.com/css/adjacentsiblingselector