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

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 17:44:29450browse

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>

Example CSS:

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

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>

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!

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