Home >Web Front-end >CSS Tutorial >How to Center Divs Horizontally Within a Container?

How to Center Divs Horizontally Within a Container?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 14:54:29756browse

How to Center Divs Horizontally Within a Container?

Horizontal Alignment of Divs Within a Container

When attempting to center divs horizontally within a container, one may face difficulties. This is often due to the default behavior of float: left.

To address this issue, consider using display: inline-block instead of float for the divs. This technique eliminates the need for manual calculation of margins and allows for responsive alignment.

For instance, in the following CSS:

<code class="css">.row {
  width: 100%;
  margin: 0 auto;
}
.block {
  width: 100px;
  display: inline-block;
}</code>

The div with class "block" will behave as an inline element and will align itself horizontally within the container div with class "row".

Additionally, for cases where there is a row div with only one block div, you can center it using text-align: center:

<code class="css">.row-with-single-block {
  text-align: center;
}</code>

The above is the detailed content of How to Center Divs Horizontally Within a 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