Home > Web Front-end > CSS Tutorial > How Can I Make Two Floating Divs the Same Height Using Only CSS?

How Can I Make Two Floating Divs the Same Height Using Only CSS?

Barbara Streisand
Release: 2024-12-12 17:42:16
Original
627 people have browsed it

How Can I Make Two Floating Divs the Same Height Using Only CSS?

Making Two Floating Divs the Same Height in HTML/CSS

Introduction

Achieving equal height in divs can be challenging, especially when they are side-by-side and have different content lengths. One common workaround is using tables, but this approach may not be semantically appropriate.

Using CSS to Create Equal Height Divs

To achieve equal height without using tables, CSS provides several techniques. One approach involves setting large bottom padding, negating that padding with negative bottom margin, and surrounding the divs with a container with hidden overflow.

Implementation

To demonstrate this technique, consider the following CSS code:

#container {
  overflow: hidden;
  width: 100%;
}

#left-col {
  float: left;
  width: 50%;
  background-color: orange;
  padding-bottom: 500em;
  margin-bottom: -500em;
}

#right-col {
  float: left;
  width: 50%;
  margin-right: -1px; /* for IE compatibility */
  border-left: 1px solid black;
  background-color: red;
  padding-bottom: 500em;
  margin-bottom: -500em;
}
Copy after login

In the HTML, create the div container and two child divs:

<div>
Copy after login

This approach essentially forces the two divs to have the same height, even if they contain different amounts of content. The large bottom padding and negative margin cancel each other out, allowing the divs to take up only the vertical space they need. The container with hidden overflow ensures that any excess content is not visible.

Conclusion

This CSS technique provides a semantically correct way to create equal height floating divs in HTML/CSS. It effectively mimics the behavior of a table without introducing unnecessary markup.

The above is the detailed content of How Can I Make Two Floating Divs the Same Height Using Only CSS?. 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