Richard
Richard

Reputation: 65530

CSS: floated elements give zero height on the containing element

I am confused by the fact that applying float to li elements seems to mean that the containing ul element has no height. You can see the problem demonstrated in this jsFiddle.

Basically, I would like to create a ul with an arbitrary number of li elements. I would like each li element to have a width of 20%, so I end up with five li elements per line.

I would also like the ul element to have some height, so I can apply a bottom border.

If I use this class on the lis:

.result1 { 
  width: 20%;
  float: left;
} 

then the ul has a height of 0. I've seen posts recommending display: inline-block, but if I use this instead:

.result2 { 
  width: 20%;
  display: inline-block;
}

then the ul has height, but there is whitespace between the lis so they break over two lines.

This must be something in the CSS spec that I'm failing to understand. How can I get five elements per line, with height on the containing element?

Upvotes: 1

Views: 688

Answers (2)

user2129623
user2129623

Reputation: 1256

Add overflow: hidden; to the parent <ul class="results">

Fiddle

Upvotes: 5

ashley
ashley

Reputation: 2767

Floated elements cause the parent to collapse, you need to clear the parent element.

.results:after {
  content: "";
  display: table;
  clear: both;
}

http://jsfiddle.net/CuCdr/1/

Upvotes: 2

Related Questions