Home > Web Front-end > CSS Tutorial > Why do my divs not center horizontally within the containing div?

Why do my divs not center horizontally within the containing div?

Linda Hamilton
Release: 2024-11-02 17:44:29
Original
516 people have browsed it

Why do my divs not center horizontally within the containing div?

Centering Horizontal DIV Alignment

You've encountered an issue where your divs fail to align horizontally within the containing div. Here's a common query and solution:

Question

Why do my divs not center horizontally within the containing div?

Example HTML:

<code class="html"><div class="row">
  <div class="block">Lorem</div>
  <div class="block">Ipsum</div>
  <div class="block">Dolor</div>
</div></code>
Copy after login

Example CSS:

<code class="css">.row {
  width: 100%;
  margin: 0 auto;
}
.block {
  width: 100px;
  float: left;
}</code>
Copy after login

Solution

To achieve horizontal centering, consider using display: inline-block instead of float. This method enables divs to behave like inline elements while maintaining block-level properties such as width and height.

Updated CSS:

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

With this modification, your divs should align horizontally within the containing div.

The above is the detailed content of Why do my divs not center horizontally within the containing div?. 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