Skip to content Skip to sidebar Skip to footer

Styling A Nested List In Css

According to this well-rated SO post Proper way to make HTML nested list? the best-practice way to make a nested list is this:
  • List item one

Solution 1:

Apply line-height instead of height

ulli {
  background-color:yellow;
  line-height:40px;
}

ullili {
 background-color:red;
 line-height:40px;
}

height:40px will apply 40px for all the listed items, so that two clild 'li' wont fit inside the 40px of the parent 'li'

Solution 2:

The way you have given here, is not a valid syntax:

<ul><li>List item one</li><li>List item two with subitems:</li><!-- Problem here... --><ul><li>Subitem 1</li><li>Subitem 2</li></ul><li>Final list item</li></ul>

You cannot nest <ul> directly under <ul> in this case. You need to do is:

<ul><li>List item one</li><li>List item two with subitems:
    <ul><li>Subitem 1</li><li>Subitem 2</li></ul></li><li>Final list item</li></ul>

And the above code is perfectly valid. You don't need to use a height but try using min-height. I strongly advice you against using height (as that has to be calculated by the contents).

Solution 3:

Your code Your code :

<ul><li>List item one</li><li>List item two with subitems:
        <ul><li>Subitem 1</li><li>Subitem 2</li></ul></li><li>Final list item</li></ul>

is correct you need some changes read below:

The nested list should be inside a <li> element of the list in which it is nested.

Link to the W3C Wiki on Lists (taken from comment below): HTML Lists Wiki.

Link to the HTML5 W3C ul spec: HTML5 ul. Note that a ul element may contain exactly zero or more li elements. The same applies to HTML5 ol. The description list (HTML5 dl) is similar, but allows both dt and dd elements.

More Notes:

  • dl = definition list.
  • ol = ordered list (numbers).
  • ul = unordered list (bullets).

Solution 4:

I don't know if this is what you are looking for, but you could use min-height instead of height:

ulli {
  background-color:yellow;
  min-height: 40px;
}

ullili {
  background-color:red;
}
<ul><li>List item one</li><li>List item two with subitems:
    <ul><li>Subitem 1</li><li>Subitem 2</li></ul></li><li>Final list item</li></ul>

Of course, it could expand to higher heights if there is more content, so that is why I am not sure if that is what you are looking for.

Hope this helps.

Post a Comment for "Styling A Nested List In Css"