mysmallidea mysmallidea - 19 days ago 10
CSS Question

CSS: Select all first generation elements (children), but not grandchildren

Given this unordered list:

<ul>
<li>Level One Item One
<ul>
<li>Level One Item One</li>
<li>Level One Item Two</li>
</ul>
</li>
<li>Level One Item Two
<ul>
<li>Level Two Item One</li>
<li>Level Two Item Two</li>
</ul>
</li>
</ul>


... I would like to apply a style to all immediate
<li>
children of an
<ul>
, without having that style applied to nested list items.

I thought this CSS selector would do the trick, but it has no effect:

ul>li:not(li>ul>li) {
border: 1px solid red;
}


Here is a fiddle:

Picture of a fiddle

Just kidding, here is the fiddle: https://jsfiddle.net/nz5fdnd0/1/

Here is a picture of the desired outcome:

Screen shot of desired outcome

The desired solution would avoid using explicit class or id attributes in the HTML.

Answer

You could use

:not(li) > ul > li {
  border: 1px solid red;
}

which means target the li in a ul that is not contained (directly) in a li.

So keep in mind that if inside a li you add a div and in that a ul li it will get styled.


:not(li) > ul > li {
  border: 1px solid red;
}
<ul>
  <li>Level One Item One
    <ul>
      <li>Level One Item One</li>
      <li>Level One Item Two</li>
    </ul>
  </li>
  <li>Level One Item Two
    <ul>
      <li>Level Two Item One</li>
      <li>Level Two Item Two</li>
    </ul>
  </li>
</ul>