Home > Web Front-end > CSS Tutorial > Why Doesn't `margin: auto auto;` Vertically Center a Div?

Why Doesn't `margin: auto auto;` Vertically Center a Div?

Patricia Arquette
Release: 2024-12-11 09:08:14
Original
434 people have browsed it

Why Doesn't `margin: auto auto;` Vertically Center a Div?

Vertically Aligning a Div with margin:auto

While margin: 0 auto; can center a div horizontally, margin: auto auto; does not align it vertically as intended. Additionally, vertical-align: middle; is ineffective for block-level elements.

Why Vertical Auto Margins Fail

  • margin-top: auto and margin-bottom: auto compute to zero, providing no centering effect.
  • margin-top: -50% calculates its value relative to the containing block's width, not its height.

Workaround Using Nested Elements

One viable workaround involves nesting three elements:

.container {
    display: table;
    height: 100%;
    position: absolute;
    overflow: hidden;
    width: 100%;
}
.helper {
    position: absolute;
    top: 50%;
    display: table-cell;
    vertical-align: middle;
}
.content {
    position: relative;
    top: -50%;
    margin: 0 auto;
    width: 200px;
    border: 1px solid orange;
}
Copy after login
<div class="container">
    <div class="helper">
        <div class="content">
            <p>stuff</p>
        </div>
    </div>
</div>
Copy after login

In this solution:

  • The outer .container element establishes a table-like structure.
  • The .helper element places the content at the vertical midpoint.
  • The .content div is positioned within .helper and can be centered horizontally with margin: 0 auto;.

The above is the detailed content of Why Doesn't `margin: auto auto;` Vertically Center a 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