How To Prevent Parents of Floated Elements From Collapsing In Css

admin_img Posted By Bajarangi soft , Posted On 10-10-2020

It is known that HTML elements like div, paragraphs, texts etc. grows itself to fits the content of their child. But if the child of those elements are floatted either to right or left then the parents may collapse.

Floated Elements From Collapsing In Css

Example: Consider the below code. In the below program a parent div with a green background has 6 other child div elements. None of the parent or the childs are floatted here. Let’s compile and see the output of the code.
Example-1

<!DOCTYPE>
<html>
<head>
    <title>Floats and collapsing parents</title>
    <style>
        div{
            padding: 5px;
        }
    </style>
</head>
<body>
<!-- Parent Div -->
<div style="background-color: #ef400a;">

    <!-- Children div's begins -->
    <div>HTML5</div>
    <div>CSS3</div>
    <div>JavaScript</div>
    <div>Python</div>
    <div>MySQL</div>
    <div>MongoDB</div>
    <!-- Children div's ends -->

</div>
</body>
</html>
Example-2
<!DOCTYPE>
<html>
<head>
    <title>Floats and collapsing parents</title>
    <style>
        div{
            padding: 5px;
        }
    </style>
</head>
<body>
<!-- Parent Div -->
<div style="background-color: #60f886;">

    <!-- Children div's begins, floatted to left -->
    <div style="float: left;">HTML5</div>
    <div style="float: left;">CSS3</div>
    <div style="float: left;">JavaScript</div>
    <div style="float: left;">Python</div>
    <div style="float: left;">MySQL</div>
    <div style="float: left;">MongoDB</div>
    <!-- Children div's ends -->

</div>
</body>
</html>

Related Post