Andy
Andy

Reputation: 11462

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:

<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>

however I'm having real problems styling a list made in this way. I want each item in the list to have a specific height but I can't use li { height: 40px; } because the height of the second li also includes all the inner list. See here for an example http://jsfiddle.net/rujg3zyk.

The problem comes down to the fact that the second outer li element contains both some plain text and a block display element. This seems like a 'code smell' to me.

what's the best way of formatting this list so that each line is 40px high?

Upvotes: 2

Views: 23383

Answers (3)

Serge In&#225;cio
Serge In&#225;cio

Reputation: 1382

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

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

ul li li {
  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.

Upvotes: 0

charan kumar
charan kumar

Reputation: 2157

Apply line-height instead of height

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

ul li li {
 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'

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

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).

Upvotes: 1

Related Questions