Home > Web Front-end > CSS Tutorial > How to Vertically Center a Div within its Parent Div?

How to Vertically Center a Div within its Parent Div?

Linda Hamilton
Release: 2024-12-21 04:38:10
Original
579 people have browsed it

How to Vertically Center a Div within its Parent Div?

Centering a Div Vertically within a Parent Div

Vertically centering a div within its parent div can be achieved through various methods, without relying on specific element dimensions.

Table Layout (Classic Approach)

This method utilizes table layout and inline-block display properties.

<div class="container">
  <div class="inner">
    ...
  </div>
</div>
Copy after login
.container {
  display: table-cell;
  vertical-align: middle;
  height: 500px;
  width: 500px;
}

.inner {
  display: inline-block;
  width: 200px;
  height: 200px;
}
Copy after login

Transform (Modern Approach)

Transformations offer a simpler solution for vertical centering.

.container {
  position: relative;
  height: 500px;
  width: 500px;
}

.inner {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  height: 200px;
}
Copy after login

Flexbox (Preferred Modern Approach)

Flexbox provides the most straightforward method for centered alignment.

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 500px;
  width: 500px;
}

.inner {
  width: 200px;
  height: 200px;
}
Copy after login

Note:

  • The table layout approach is well-supported but may impact performance.
  • Transform and flexbox offer modern solutions with greater support and ease of use.
  • These methods ensure vertical centering regardless of the dimensions or content of the inner div.

The above is the detailed content of How to Vertically Center a Div within its Parent 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