How do I vertically align text in a div?
How do I vertically align text in a div?
470
24-Apr-2023
Updated on 25-Apr-2023
Aryan Kumar
25-Apr-2023To vertically align text in a div, you can use the display and align-items properties. Here's an example of how to do it:
HTML code:
CSS Code:
In this example, we're using a div with a class of container to contain the text we want to center vertically. We're setting the display property of the container element to flex to allow us to use flexbox properties to vertically align the text.
We're then using the align-items property to center the text vertically within the container element. Setting align-items: center; centers the flex items along the cross axis (which is vertical in this case).
Finally, we're using the margin: auto; property on the .text class to center the text horizontally within the container.
Note that we're also setting a height on the container element to ensure that it has a fixed height. If you don't set a height, the container element will expand to fit the text, and the text won't be vertically centered.
This method using flexbox is widely used and supported in modern browsers, but if you need to support older browsers, you may need to use other methods like using display: table-cell or absolute positioning.