Selecting a list item that does not have a sublist with CSS

advertisements

I was wondering if it is possible to select a list item that does not contain any ul's or ol's with pure CSS. Note that the list item will almost always contain an anchor, which is allowed. CSS3 can be used as well. I know how to do this with jQuery, but I'd like to use CSS(3).


First of all, there is (currently) no selector in CSS, to check if an element contains another elment or if it doesn't. (I played a bit around with :not() but it didn't work.)

But there is a trick to do this, the :only-child selector. If you can say that there will always be an <a> tag in your list and no other element than an <ul>, you can do it like this:

HTML

<ul class="list">
    <li><a href="#">Test</a></li>
    <li>
        <a href="#">Test</a>
        <ul>
            <li>Test2</li>
        </ul>
    </li>
</ul>

CSS

.list > li > a:only-child { color: red; }

So you select all <a> tags which are the only child of their parent tag.

This might not be the perfect solution, but will work if you have a structure like my HTML code.

Have a look at my jsfiddle to see the solution: http://jsfiddle.net/2Lxaah61/