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.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To 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.