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

How to Vertically Center a Div in CSS?

Patricia Arquette
Release: 2024-12-11 04:28:09
Original
996 people have browsed it

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;
}
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 How to Vertically Center a Div in CSS?. 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