Home >Web Front-end >CSS Tutorial >How Can I Align Floated Divs Horizontally Within a Fixed-Sized Container?

How Can I Align Floated Divs Horizontally Within a Fixed-Sized Container?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-08 13:03:02246browse

How Can I Align Floated Divs Horizontally Within a Fixed-Sized Container?

Aligning Floated Divs Horizontally

When working with a container div with a fixed size and overflow hidden, aligning floated divs horizontally can be a challenge. By default, floated divs will wrap onto the next line when reaching the right boundary of their parent, even if there's space available above.

Desired Appearance

The desired appearance is a horizontal row of divs within the container, preventing them from wrapping onto multiple lines. Inline elements with white-space: no-wrap can achieve this, but it's not suitable for floated block-level elements.

Solution

To address this, you can introduce an inner div within the container that has sufficient width to accommodate all the floated divs. By setting the overflow property to hidden on both the container and the inner div, you can prevent the divs from spilling out of the designated area.

Example Code

#container {
  background-color: red;
  overflow: hidden;
  width: 200px;
}

#inner {
  overflow: hidden;
  width: 2000px;
}

.child {
  float: left;
  background-color: blue;
  width: 50px;
  height: 50px;
}

The above is the detailed content of How Can I Align Floated Divs Horizontally Within a Fixed-Sized Container?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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