OneBite.Dev - Coding blog in a bite size

center text vertically css

Code snippet for how to center text vertically css with sample and detail explanation

Understanding how to vertically align text using CSS is an invaluable skill when it comes to web page designing. This article provides an easy guide illustrating how to center text vertically using CSS.

Code snippet for vertical text centering

.container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.text {
    text-align: center;
}

In this sample CSS code, we are centering text vertically in a div class .container and the text to be centered is within a class called .text.

Code Explanation for vertical text centering

This code is quite simple to understand if you have a basic idea on how CSS works. The .container is set to display: flex; which turns the div into a flexible container box. This box then lets us align the items both vertically and horizontally.

The property justify-content: center; is applied to align the child elements of the container horizontally at the center.

The align-items: center; is the property that does the vertical aligning. It places the child elements at the center of the container, and in this case, it centers them vertically because display: flex; is applied to the container.

The height: 100vh; ensures that the container takes up 100% of the viewport’s height hence making our text vertically centered throughout the entire page or screen.

Finally, the .text class within the child elements of the container is set text-align: center; which ensures the text is centered horizontally.

This is a simple and straightforward way of vertically centering text using CSS. However, different methods can be used depending on the specific requirements and structure of your webpage.

css