Home > Article > Web Front-end > 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!