How to Vertically Center Content Within a Div with Defined Dimensions?

DDD
Release: 2024-11-12 11:23:02
Original
404 people have browsed it

How to Vertically Center Content Within a Div with Defined Dimensions?

Centering Content Vertically Within a Div with Defined Dimensions

When working with a div of predefined width and height, vertically aligning its content can be a common challenge. One requires a method that effectively centers content of varying heights.

Solutions:

1. Parent Div as Table-Cell:

Set the parent div's display to table-cell. This eliminates the need for table-cell on the content itself:

.area {
  display: table-cell;
  vertical-align: middle;
}
Copy after login

2. Parent Div as Block, Content Div as Table-Cell:

Set the parent div's display to block and the content div's display to table-cell:

.area {
  display: block;
}

.content {
  display: table-cell;
  vertical-align: middle;
}
Copy after login

3. Parent Div Floating, Content Div as Table-Cell:

Set the parent div to float and the content div as a table-cell. This requires careful consideration of margins:

.area {
  float: left;
}

.content {
  display: table-cell;
  vertical-align: middle;
}
Copy after login

4. Parent Div Positioned Relative, Content Div Positioned Absolute:

Set the parent div's position to relative and the content div's position to absolute. Determine the content height and set the margin-top to half of the content height. This solution requires manual adjustment for each case:

.area {
  position: relative;
}

.content {
  position: absolute;
  top: 50%;
  height: 50%;
  margin-top: -25%;
}
Copy after login

The above is the detailed content of How to Vertically Center Content Within a Div with Defined Dimensions?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template