Home > Web Front-end > CSS Tutorial > Can I Vertically Center a DIV Using `margin: auto`?

Can I Vertically Center a DIV Using `margin: auto`?

Patricia Arquette
Release: 2025-01-03 12:36:43
Original
209 people have browsed it

Can I Vertically Center a DIV Using `margin: auto`?

Vertically Aligning a DIV with margin: auto

Question:

Is it possible to center a DIV vertically using margin:auto auto;? Why doesn't vertical-align:middle; work?

Answer:

Regarding Margin:

Unfortunately, margin:auto auto; does not achieve vertical centering. Margins are not applicable to block-level elements like DIVs for vertical alignment. As a result, margin:top:auto and margin-bottom:auto are ineffective.

Regarding vertical-align:middle;:

vertical-align:middle; is only applicable to inline elements, not block-level elements like DIVs.

Workaround:

Since it's not possible to vertically center a DIV using margins, a workaround solution is recommended. One approach that works well is to use nested elements within a table-like container:

.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

The above is the detailed content of Can I Vertically Center a DIV Using `margin: auto`?. 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