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
Barbara StreisandOriginal
2024-12-23 18:22:14318browse

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;
}

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;
}

Using Transform Property

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

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

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!

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