Why Does a Parent Div Have Zero Height with Floated Children?

Mary-Kate Olsen
Release: 2024-11-10 06:59:02
Original
321 people have browsed it

Why Does a Parent Div Have Zero Height with Floated Children?

Understanding the Height of a Parent Div with Floated Children

In the context of web design, the height of a div container can be influenced by its child elements. However, when those child elements are floated, an unexpected behavior can occur, resulting in a parent div with zero height.

To illustrate this, consider the following CSS:

#wrapper {
  width: 75%;
  min-width: 800px;
}
.content {
  text-align: justify;
  float: right;
  width: 90%;
}
.lbar {
  text-align: justify;
  float: left;
  width: 10%;
}
Copy after login

When you create HTML using this CSS, for example:

<div>
Copy after login

You may notice that the page renders correctly, but when you inspect the DOM, the "#wrapper" div appears to have a height of 0px. This is because floated content removes itself from the normal flow of the document, essentially becoming removed from the document tree.

The consequence of this is that the parent div's height is not influenced by its floated children. As a result, the parent div remains at its default height of 0px.

To resolve this issue and ensure the parent div expands to encompass its floated content, you can use the "overflow: hidden" property on the parent div. This creates a new "block formatting context," which forces the floated children to remain within the parent's bounds.

Here's the updated CSS:

#wrapper {
  width: 75%;
  min-width: 800px;
  overflow: hidden; /* Added */
}
Copy after login

With this modification, the "#wrapper" div will now stretch to fit its floated children, allowing the page's layout to behave as expected.

The above is the detailed content of Why Does a Parent Div Have Zero Height with Floated Children?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template