How do I make a div height depend on the content inside?
Solution 1
You have two options:
<div class="container" style="overflow:hidden">
<div style="float:left; height:100px;">
<div style="float:left; height:100px;">
</div>
or
<div class="container">
<div style="float:left; height:100px;">
<div style="float:left; height:100px;">
<div style="clear:left">
</div>
Note that overflow:hidden
elements will wrap around floating inner elements. Alternatively, you can use an element to clear the float, which will also make the surrounding element to wrap it's content.
Another tip: You don't have to state that divs are display:block
. In HTML, there are basically 2 types of elements, block
and inline
. Divs are block
by default.
Solution 2
Add overflow:hidden
to that DIV.
Related videos on Youtube
Emmett
Updated on September 15, 2022Comments
-
Emmett over 1 year
I have nested
div
s, with most beingfloat:left; display:block;
, like do:<div class="container" style="display:block;"> <div style="float:left; display:block; height:100px;"> <div style="float:left; display:block; height:100px;"> </div>
I want the
div
container to get bigger without setting a height. At the moment it's a flat line.
How do I set up the innerdiv
s, so that the container has a height?TL;DR: Currently I can see the 2 inside
div
's fine, but the container is a flatdiv
(no height).
How do I give it a height? -
Bram Vanroy over 11 yearsDo note that the value for the overflow attribute can be any value that is applicable (auto, hidden, scroll, visible).
-
Paul Sullivan over 11 yearsduplicate of stackoverflow.com/questions/804926/…
-
Paul Sullivan over 11 yearsYou can also float the container left or add a cleared element at the end (though I recommend using a clearfix solution)
-
Scott Simpson over 11 yearsOverflow: hidden can cause issues when you don't want the overflow to be hidden. (if you have a flyout for example). Clearfix is a good way to go as well.
-
casraf over 11 yearsUsually with floats you can't actually overflow, since you want it to fit, unless you add
max-height
or something, in which case,overflow:auto
does the trick -
bfavaretto over 11 yearsAlso, any floated element becomes a block.