Home >Web Front-end >CSS Tutorial >How to Vertically Center a Div in CSS?

How to Vertically Center a Div in CSS?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-11 04:28:09989browse

How to Vertically Center a Div in CSS?

Vertically Centering a Div with margin:auto

While margin:O auto; horizontally centers a div, margin:auto auto; does not center it vertically. Unfortunately, vertical-align:middle; also doesn't work for block-level elements like divs.

Limitations:

  • vertical-align:middle;: Not applicable to block-level elements.
  • margin-top:auto and margin-bottom:auto: Computed values are zero.
  • margin-top:-50%;: Percentage-based margin values are based on the containing block's width.

Vertical Centering Workarounds:

Due to the nature of document flow and element height calculations, it's impossible to use margins for vertical centering within a parent element. These workarounds, however, can resolve the issue:

Nested Element Approach:

This requires nesting three elements as follows:

.container {
  display: table;
  height: 100%;
  position: absolute;
  overflow: hidden;
  width: 100%;
}

.helper {
  display: table-cell;
  vertical-align: middle;
  position: absolute;
  top: 50%;
}

.content {
  position: relative;
  top: -50%;
  margin: 0 auto;
  width: 200px;
  border: 1px solid orange;
}
<div class="container">
  <div class="helper">
    <div class="content">
      <p>stuff</p>
    </div>
  </div>
</div>

The above is the detailed content of How to Vertically Center a Div in CSS?. 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