Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Containing div smaller than children

Tags:

css

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

like image 569
Eric J. Avatar asked Feb 07 '13 19:02

Eric J.


People also ask

How do I make a div smaller than its contents?

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

How do you make a parent div the same height as a child?

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.

Do DIVs inherit height?

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.


1 Answers

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/

like image 127
Jrod Avatar answered Sep 30 '22 04:09

Jrod