How can I select an tag that has a sibling

2019-06-07 19:09发布

问题:

HTML is like this:

<ul>
    <li>
        <a>Menu 1</a>
    </li>
    <li>
        <a>Menu 2</a>
        <ul>
            <li>Sub menu 2</li>
        </ul>
    </li>
    <li>
        <a>Menu 1</a>
    </li>
</ul>

How can I select an <a> tag that has a sibling <ul> tag after it, with pure CSS?

(Which, in the example above, will be <a>Menu 2</a>.)

回答1:

Unfortunately, I don’t think you can.

  • CSS 2 includes the adjacent sibling selector (+), which allows you to select an element that immediately follows another element.

    E.g. a + ul would select your <ul> containing the text “Sub menu 2”

  • CSS 3 includes the general sibling selector (~), which allows you to select an element that follows another element, even if there are elements in between them.

    E.g. a + ul would select your <ul> containing the text “Sub menu 2” even if there was a <span> between the <a> and the <ul>

But neither has a selector that lets you select an element which has specific elements following it.



回答2:

Possibly via nth-child

ul li:nth-child(2) a { color:#009; }

Selects the second list item, then subsequent anchor tags.

DEMO HERE



回答3:

Here is a jsFiddle file you can reference LINK

CSS

ul > li > a {color:red}

ul > li > ul  {color:blue}​

HTML

<ul>
    <li>
        <a>Menu 1</a>
    </li>
    <li>
        <a>Menu 2</a>
        <ul>
            <li>Sub menu 2</li>
        </ul>
    </li>
    <li>
        <a>Menu 1</a>
    </li>
</ul>​