dragonore
dragonore

Reputation: 803

Select only parent element of unordered list minus the sub list using css selectors?

Just trying to style the first ul li a only without styling the sub ul li a. I realize there is no such thing as parent selectors in CSS and proably for good reasons, so how would I accomplish this without assigning all of the li's a class? Maybe this is impossible, which is why I am asking. Here is the HTML.

<div id="myDiv">
    <h2>Headline 2</h2>

    <div>
        <p>Some Paragraph 1</p>
        <ul class="list">
            <li><a href="#">List 1 Item 1 (=)</a></li>
            <li><a href="#">List 1 Item 2 (=)</a>
                <ul>
                    <li><a href="#">List 1 Item 2a</a></li>
                    <li><a href="#">List 1 Item 2b</a></li>
                </ul>
            </li>
            <li><a href="#">List 1 Item 3 (=)</a></li>
        </ul>
    </div>

    <p>Some paragraph 2</p>
    <div>
        <ul>
            <li><a href="#">List 2 Item 1</a></li>
            <li><a href="#">List 2 Item 2</a></li>
        </ul>
    </div>
</div>

Here is what I would like to target enter image description here

Again, I realize I could just add classes to all of them and get the result I want, I just want to know if there is another way.

Using css selectors, here is how I could target the sublist (not what I want)

ul.list li > ul li a{
   ...
}

Targeting the first ul plus the sublist (not what I want)

ul.list > li a{
   ...
}

enter image description here

Here is a fiddle for you convience.
http://jsfiddle.net/94e2fo30/

Upvotes: 1

Views: 1795

Answers (2)

Gisheri
Gisheri

Reputation: 1715

#myDiv > div > ul > li > a{color:red}

since both your parent li's are direct children of ul's which are direct children of divs which are children of #myDiv

This will work in your case, but I wouldn't recommend doing it. Anytime css starts too look like this you'll want to rethink your organization

Upvotes: 0

Maria Ines Parnisari
Maria Ines Parnisari

Reputation: 17506

The difference between the first list and its sublist is that the first is preceded by a p.

p + ul > li > a {
    color: red;
}

will give:

enter image description here

Upvotes: 1

Related Questions