"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Center Text Vertically Within a Div?

How to Center Text Vertically Within a Div?

Published on 2024-12-11
Browse:663

How to Center Text Vertically Within a Div?

How to Vertically Align Text in a Div

When working with a div, it's sometimes necessary to ensure that the text within it is aligned vertically in the middle. This can be achieved through various methods.

Using line-height

If the div has a fixed height, such as 50px, you can simply use the line-height CSS property.

#abc {
  height: 50px;
  line-height: 50px;
}

This will center the text vertically within the div.

Using display properties

For multi-line text, you can wrap it in a span element and apply display properties and vertical-align.

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

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

Using the transform property

Another method involves using the transform property with the translateY() function. This is especially useful for older browsers that don't support display properties.

#abc {
  position: relative;
}

#abc p {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3