- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do you keep parents of floated elements from collapsing in CSS?
To prevent parents of floated elements from collapsing, first, we will try to understand what the problem is. After that, we will work around the examples i.e.
- How parents of floated elements collapse?
- Prevent parents of floated elements to collapse using the Overflow Property
- Prevent parents of floated elements to collapse using the Height Property
How parents of floated elements collapse
Example
Let us first understand how parents of floated elements collapse. Here’s an example −
<html> <head> <title>Example</title> <style> div{ padding: 10px; } </style> </head> <body> <h1>Nested Divs</h1> <div style="background-color: orange;"> <div>One</div> <div>Two</div> <div>Three</div> </div> </body> </html>
Output
Now, set float: left for the child divs. This will lead the parent div collapse −
<div style="background-color: orange;"> <div style="float: left;">One</div> <div style="float: left;">Two</div> <div style="float: left;">Three</div> </div>
Output
Prevent parents of floated elements to collapse using Overflow Property
Let us now see how to keep parents of floated elements to collapse using the Overflow Property. We have set the overflow to auto value for the div −
<div style="background-color: orange; overflow: auto">
Example
Let us now see the complete example −
<html> <head> <title>Example</title> <style> div{ padding: 10px; } </style> </head> <body> <h1>Nested Divs</h1> <div style="background-color: orange; overflow: auto"> <div style="float: left;">One</div> <div style="float: left;">Two</div> <div style="float: left;">Three</div> </div> </body> </html>
Output
Prevent parents of floated elements to collapse using the height property
Let us now see how to keep parents of floated elements to collapse using the height Property. We have set the height property for the div −
<div style="background-color: orange;height: 40px">
Example
Let us now see the complete example −
<html> <head> <title>Example</title> <style> div{ padding: 10px; } </style> </head> <body> <h1>Nested Divs</h1> <div style="background-color: orange;height: 40px"> <div style="float: left;">One</div> <div style="float: left;">Two</div> <div style="float: left;">Three</div> </div> </body> </html>
Output
Advertisements