Reputation: 724
This is a basic design question, which has vexed me for along time. Imagine this code:
<div style='background:#ccc;'>
<ul>
<li style='display:block; float:left; width:50%;'> item 1 </li>
<li style='display:block; float:left; width:50%;'> item 2 </li>
<li style='display:block; float:left; width:50%;'> item 3 </li>
<li style='display:block; float:left; width:50%;'> item 4 </li>
<li style='display:block; float:left; width:50%;'> item 5 </li>
<li style='display:block; float:left; width:50%;'> item 6 </li>
</ul>
</div>
The <ul>
element will outgrow the container unless I set the containing div to also have the css properties of "float:left;"
(Please note that I do not style my elements inline, this is simply for the example).
Often, I work-around this by giving the container an explicit height... but this feels sloppy in a mobile world, and creates a lot of overhead: I must write media queries to control the height at various screen sizes. What is the right way to have auto height on an element which contains floating elements?
Upvotes: 1
Views: 37
Reputation: 208032
Set overflow:auto
on the containing div:
<div style='background:#ccc;overflow:auto;'>
<ul>
<li style='display:block; float:left; width:50%;'> item 1 </li>
<li style='display:block; float:left; width:50%;'> item 2 </li>
<li style='display:block; float:left; width:50%;'> item 3 </li>
<li style='display:block; float:left; width:50%;'> item 4 </li>
<li style='display:block; float:left; width:50%;'> item 5 </li>
<li style='display:block; float:left; width:50%;'> item 6 </li>
</ul>
</div>
When you float the children, the ancestor collapses and setting the overflow restores the behavior you're after.
Upvotes: 3