Fixing the Collapsed Parent using CSS

One of the many problems that developers face while using CSS float property is that if all child elements are floated then the parent container will collapse. To avoid parent container collapsing we can use one of the following solutions.


Parent containers are collapsed as all content is floated inside them. Only the padding of container is seen due to CSS background-color property.


Following is the problem code which need rectification −

 Live Demo

<!DOCTYPE html>
<title>Avoid Parent Container Collapse</title>
   background-color: grey;
   border: 4px solid black;
#navbar, #content{
   padding: 12px;
   color: white;
   background-color: #C303C3;
li {
   list-style: none;
   border: 2px solid black;
   background-color: grey;
   text-align: center;
   float: left;
#content {
   background-color: #4CAF50;
#leftContent, #rightContent {
   border: 3px solid black;
#leftContent {
   width: 45%;
   float: left;
#rightContent {
   width: 45%;
   float: right;
<div id="navbar">
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
<li>Link 4</li>
<div id="content">
<div id="leftContent">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
<div id="rightContent">
Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


Following is the output for problem -

Solution 1

We can apply CSS float: left to the parent container of the floated elements.

This solution rectifies the problem to an extant as now the parent of the parent element is collapsed and the parent element of floated content is wrapped around child elements.

Following is the output for solution 1 −

Solution 2

We can use CSS overflow property on the parent container of floated elements. This solution works well but is not used as this lacks logical reasoning.

Following is the output for solution 2 −

Solution 3

We can add an empty div at the bottom inside of the parent container with a class ‘clearfix’ having the following content.

.clearfix {
   clear: both;

This solution rectifies the problem but now the an empty div element is present at the bottom inside of parent container which is representing nothing.

Following is the output for solution 3 −

Solution 4

We can add a class that uses pseudo element ‘after’ to the parent container having the following content −

.clearfix {
.clearfix::after {
   content: '';
   display: table;
   clear: both;

Following is the output for solution 4 −