WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to fix the issue of CSS collapsing parent having floating children

Topic: HTML / CSSPrev|Next

Answer: Use the CSS clear property

When float property applied to the element inside the non floated parent, the parent element doesn't stretch up automatically to accommodate the floated elements. This behavior is typically known as collapsing parent. This is not always obvious if you do not apply some visual properties like background or borders to the parent elements, but it is important to be aware of and must dealt with to prevent strange layout and cross-browser problems.

The CSS :after pseudo-element in conjunction with the content property is used to resolve the collapsing parent issues in the browsers like Firefox, Chrome, Safari, etc.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fixing Collapsing Parent Issue</title>
<style> 
    .clearfix:after{
        content:".";
        display:block;
        height:0;
        clear:both;
        visibility:hidden;
    }
    .container{
        background:yellow;
        border: 1px solid #000000;      
    }
    .column-left, .column-right{
        width: 200px;        
        margin: 10px;
        padding: 10px;
    }
    .column-left{
        float: left;       
        background: #ff0000
    }
    .column-right{
        float: right;
        background: #00ff00;
    }
</style>
</head>
<body>
    <div class="container clearfix">
        <div class="column-left">Floated to left.</div>
        <div class="column-right">Floated to right.</div>
    </div>
</body>
</html>

Check out the tutorial on CSS alignment for more solutions on fixing collapsing parents.


Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties