Given the following
#container {
border:solid 3px red;
}
#left {
float: left;
background-color: lightblue;
height: 300px;
}
#right {
float: left;
background-color: coral;
height: 300px;
}
<div id='container'>
<div id='left'>Left content</div>
<div id='right'>Right content</div>
</div>
(See: http://jsfiddle.net/ericjohannsen/JCPEH/1/)
Why does container
apparently not have any area (that is, it has a zero height, plus the border)? I naively expected it to be as tall as the child div
s that it contains.
What is the proper way to set this up so that the div
containing the two children is as tall as the children?
Answer: Use the CSS display Property You can simply use the CSS display property with the value inline-block to make a <div> not larger than its contents (i.e. only expand to as wide as its contents).
Using height: auto or using min-height on parent element will work. And for avoiding horizontal scrollbar, which can be caused due to padding or border can be avoided by using box-sizing: border-box on child element or overflow: hidden on parent element.
The div1 has a height set to 100px and a color set to red . The color will be inherited by the child elements. The height property is not inheritable, so the child elements won't inherit it.
You need to clear your floats. You can do this via a clearfix class:
.clearfix:before,
.clearfix:after {
content: " ";
display: table;
}
.clearfix:after {
clear: both;
}
.clearfix {
*zoom: 1;
}
#container {
border:solid 3px red;
}
#left {
float: left;
background-color: lightblue;
height: 300px;
}
#right {
float: left;
background-color: coral;
height: 300px;
}
<div id='container' class="clearfix">
<div id='left'>Left content</div>
<div id='right'>Right content</div>
</div>
or a clearing element:
.clear {
clear:both;
}
#container {
border:solid 3px red;
}
#left {
float: left;
background-color: lightblue;
height: 300px;
}
#right {
float: left;
background-color: coral;
height: 300px;
}
<div id='container'>
<div id='left'>Left content</div>
<div id='right'>Right content</div>
<div class="clear"><!-- --></div>
</div>
Updated Fiddle: http://jsfiddle.net/JCPEH/5/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With