Table of Contents
There are several ways to vertically align text in a div using CSS. Here are two possible approaches:
Approach 1: Using Flexbox
Flexbox is a useful CSS layout module that provides a simple and flexible way to vertically align elements. To vertically align text in a div using flexbox, follow these steps:
1. Create a container div that will hold the text and apply the following CSS properties to it:
.container { display: flex; align-items: center; justify-content: center; }
2. Place the text inside the container div:
<div class="container"> <p>Vertically aligned text</p> </div>
Related Article: How to Vertically Align Text Within A Div Using CSS
Approach 2: Using Table Display
Another approach to vertically align text in a div is by using table display properties. Here's how you can do it:
1. Create a container div and apply the following CSS properties to it:
.container { display: table; }
2. Place the text inside a child div and apply the following CSS properties to it:
.child { display: table-cell; vertical-align: middle; }
3. Place the child div inside the container div:
<div class="container"> <div class="child"> <p>Vertically aligned text</p> </div> </div>
Best Practices
Related Article: How to Horizontally Center a Div in CSS
- Use flexbox when you need more flexibility in your layout, such as aligning multiple elements vertically.
- Use table display when you have a simple layout and need to vertically align a single element.