CSS HTML

[Solved – 7 Answers] How do you keep parents of floated elements from collapsing

The elements like

s normally grow to fit their contents, using the float property can cause a startling problem for CSS newbies: if floated elements have non-floated parent elements, the parent will collapse.
For example:
html code
div>
    <div style="float: left;">Div 1</div>
    <div style="float: left;">Div 2</div>
</div>
  • The parent div in this example will not expand to contain its floated children – it will appear to have height: 0.

How to solve this problem?

Float the parent.

html code
<div style="float: left;">
    <div style="float: left;">Div 1</div>
    <div style="float: left;">Div 2</div>
</div>

Give the parent an explicit height.

 

html code
div style="height: 300px;">
    <div style="float: left;">Div 1</div>
    <div style="float: left;">Div 2</div>        
</div>

Append a “spacer” element inside the parent element, like this:

html code
<div>
    <div style="float: left;">Div 1</div>
    <div style="float: left;">Div 2</div>
    <div class="spacer" style="clear: both;"></div>
</div> 

Set parent to overflow: auto

html code
<div style="overflow: auto;">
    <div style="float: left;">Div 1</div>
    <div style="float: left;">Div 2</div>        
</div>

  • The problem happens when a floated element is within a container box, that element does not automatically force the container’s height adjust to the floated element. When an element is floated, its parent no longer contains it because the float is removed from the flow.
  • You can use 2 methods to fix it:
css code
{ 
clear: both; 
}
clearfix
  • use the method below to “clearfix” it.
css code
clearfix:after
{
    content: ".";
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
}
.clearfix 
{
    display: inline-block;
}
html[xmlns] .clearfix 
{
    display: block;
}
* html .clearfix 
{
    height: 1%;
}

See also  [Solved-11Answes] How to give text or an image a transparent background using CSS

using a clearfix class for parent element

css code
clearfix:after 
{
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}
.clearfix 
{
    display: inline-block;
}
* html .clearfix 
{
    height: 1%;
}
.clearfix 
{
    display: block;
}

  • Add this in the parent div at the bottom
html code
<div style="clear:both"></div>

About the author

Wikitechy Editor

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

2 Comments

Click here to post a comment

X