The text-align property in CSS controls the horizontal alignment of text within a block element.
Basic Usage
Here’s a simple example:
p {
text-align: center;
}
This code will center the text within all paragraph elements on the page.
Available Values
- left: Aligns text to the left (default)
- right: Aligns text to the right
- center: Aligns text to the center
- justify: Distributes text evenly across the line, except for the last line
- initial: Sets the property to its default value
- inherit: Inherits the property from the parent element
Example
<div class="container">
<p>This text is left-aligned (default).</p>
<p class="centered">This text is centered.</p>
<p class="justified">This text is justified.</p>
</div>
.centered {
text-align: center;
}
.justified {
text-align: justify;
}
Important Notes
text-alignapplies to block-level elements like<p>,<div>,<h1>, etc.- It doesn’t affect inline elements like
<span>. - For vertical alignment, you’ll need to use different properties or techniques like Flexbox or Grid.
Additional Tips
- Use
text-align: justifyfor newspaper-style text columns. - Combine
text-alignwith other CSS properties for more complex layouts.
Example of centering an image using text-align:
HTML
<div class="image-container">
<img src="image.jpg" alt="Image">
</div>
image-container {
text-align: center;
}
By setting text-align: center on the container, the image will be centered within it.