How to center text in CSS
To center text in CSS, you can use the text-align
property. The text-align
property specifies the horizontal alignment of text within its container. Here’s how to center text horizontally and vertically using different techniques:
- Centering Text Horizontally:
To center text horizontally, you can set thetext-align
property of the container element tocenter
.
HTML:
<div class="centered-text">
This text will be centered horizontally.
</div>
CSS:
.centered-text {
text-align: center;
}
In this example, the text within the .centered-text
div will be centered horizontally.
- Centering Text Vertically and Horizontally using Flexbox:
To center text both horizontally and vertically, you can use Flexbox.
HTML:
<div class="centered-container">
<p class="centered-text">This text will be centered vertically and horizontally.</p>
</div>
CSS:
.centered-container {
display: flex;
justify-content: center;
align-items: center;
height: 200px; /* Set a height for the container to vertically center the text */
}
.centered-text {
text-align: center;
}
In this example, the .centered-container
div becomes a Flexbox container, and the justify-content: center;
and align-items: center;
properties are used to center the child .centered-text
element both horizontally and vertically within the container.
- Centering Text Vertically and Horizontally using Grid Layout:
Alternatively, you can use CSS Grid to center text both horizontally and vertically.
HTML:
<div class="centered-container">
<p class="centered-text">This text will be centered vertically and horizontally.</p>
</div>
CSS:
.centered-container {
display: grid;
place-items: center;
height: 200px; /* Set a height for the container to vertically center the text */
}
.centered-text {
text-align: center;
}
In this example, the .centered-container
div becomes a Grid container, and the place-items: center;
property is used to center the child .centered-text
element both horizontally and vertically within the container.
Using these techniques, you can easily center text both horizontally and vertically, ensuring a visually balanced and appealing design for your web page.