To vertically align text within a div
in CSS, you can use the display: flex;
property along with the align-items
property or the line-height
property. Here are two common methods:
css.container {
display: flex;
align-items: center; /* Vertical alignment */
}
/* Optional: Center horizontally as well */
.container {
display: flex;
justify-content: center; /* Horizontal alignment */
align-items: center; /* Vertical alignment */
}
css.container {
height: 100px; /* Set a fixed height for the container */
line-height: 100px; /* Equal to the container height */
text-align: center; /* Center the text horizontally */
}
In the first method, the display: flex;
property is applied to the container, and align-items: center;
is used to vertically center the text within the container. You can also use justify-content: center;
to center the text horizontally as well.
In the second method, a fixed height is set for the container, and the line-height
property is set to the same value. This will vertically center the text within the container. Adjust the height value as needed.
Choose the method that best fits your layout and design requirements. The flexbox method is more flexible and widely used, while the line-height method is simpler and might be suitable for specific scenarios.