Jason Foglia
Jason Foglia

Reputation: 2521

How could I use pseudo-element :after :before conditionally

If I wanted to only insert a pseudo-element after a link only if the link is followed by another element say ul. How could I do this?

Example:

<ul>
    <li>
        <a href="#">blah<!-- insert -> here with CSS --></a>
        <ul>
            <li>More stuff</li>
        </ul>
    </li>
    <li>
        <a href="#">blah 2<!--Do nothing here--></a>
    </li>
</ul>

CSS I wish could happen:

ul li a:after if(next:ul) {
   content:"->";
}

I'm not trying to use JavaScript/jQuery. And I realize if conditions are not apart of css. Is there a way to do this?

Upvotes: 5

Views: 8685

Answers (3)

Zubair Hassan
Zubair Hassan

Reputation: 976

If you want to filter any element in the hierarchy/list of elements you can use the below approach.

ul li a:not(:nth-last-child(N))::after

Here N is any positive integer traversing from the end; 1 means the last element 2 means second last and so on. Instead of ul li use any selector here

For more information visit nth-last-child().

Upvotes: 0

Rob W
Rob W

Reputation: 348962

In general it is not possible to select elements based on their next sibling.

In your specific case, you can use ul li a:not(:last-child)::after, because it happens that your anchors that are not followed by an <ul> element are also the last child element.

Upvotes: 10

Simone
Simone

Reputation: 21262

You can simply use:

ul + li a:after {  /* ...css code... */  }

Basically this means:

Match an a element contained in a li element that is immediately preceded by an ul element.


The + operator in CSS is called adjacent sibling combinator.

Upvotes: 2

Related Questions