Soliah
Soliah

Reputation: 1406

Selecting all direct children of a <ul> element

Say I have:

<ul class="menu">
 <li>One</li>
  <ul class="submenu">
   <li>Apple</li>
   <li>Orange</li>
  </ul>
 <li>Two</li>
  <ul class="submenu">
   <li>Pear</li>
   <li>Banana</li>
  </ul>
</ul>

Is there a way to select only the first children of the top level <ul> element (in this case "One" and "Two") with just CSS?

Upvotes: 8

Views: 17550

Answers (4)

Cath G
Cath G

Reputation: 1

Your markup's wrong. It should be:

<ul class="menu">
 <li>One
  <ul class="submenu">
   <li>Apple</li>
   <li>Orange</li>
  </ul>
</li>

Nested lists appear inside the preceding li element

Upvotes: 0

Tarik
Tarik

Reputation: 81841

Well, if you are not worried about using jQuery, you can get over IE6 compatibility issue by using jQuery css support.

Upvotes: 0

Vic
Vic

Reputation: 12527

ul > li

But it won't work in IE6. Here is a nice list of selector support in IE versions: http://www.smashingmagazine.com/2009/10/14/css-differences-in-internet-explorer-6-7-and-8/

The simplest way to explicitly target them is to give them a separate class name.

Upvotes: 2

cletus
cletus

Reputation: 625485

Use the child selector >:

ul > li { font-weight: bold; }

The only problem is that this doesn't work in IE6. See this list of CSS selectors and browser support.

If you need to support that browser you'll have to do something like this.

ul li { font-weight: bold; }
ul li li { font-weight: normal; }

This will be relatively straightforward in some situations and completely unworkable in others. If you find yourself in a difficult situation you may need to interpose some classes to make it easier.

Upvotes: 12

Related Questions