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

How to Vertically Center Text within a Div Element?

Barbara Streisand
Release: 2024-12-23 18:22:14
Original
295 people have browsed it

How to Vertically Center Text within a Div Element?

Vertical Alignment in

Elements

To align text vertically in the middle of a

while maintaining a specific element height, multiple approaches are available:

Using Line-Height

To vertically center single-line text, apply line-height equal to the desired element height, as demonstrated in the following CSS:

#abc {
  line-height: 50px;
}
Copy after login

Using Display Properties

For multi-line text, wrap the text in a and apply display: table; and display: table-cell; along with vertical-align: middle; as follows:

#abc {
  display: table;
  width: 100%;
}

#abc span {
  vertical-align: middle;
  display: table-cell;
}
Copy after login

Using Transform Property

For more advanced alignment, consider using the transform property with translateY():

#abc {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
Copy after login

Important Notes:

  • Transform-based alignment has limited cross-browser support.
  • Ensure that the element has a defined position, such as relative or absolute, for transform positioning to take effect.

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