The text-align property in CSS is used to align text content horizontally within its container. Setting text-align: center aligns inline-level content such as text and inline elements to the center of their parent container. Centering text affects readability and responsive layout, so test across breakpoints and line lengths.
How do you center text horizontally in CSS?
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
Overview
The text-align property controls the horizontal alignment of inline or inline-block elements inside a block-level container. By setting it to center, text and other inline content are positioned in the middle of the element’s width.
Value | Description | Common Use |
|---|---|---|
left | Aligns text to the left edge of the container (default). | Used for most content. |
center | Centers text horizontally. | Used for titles, banners, and centered content blocks. |
right | Aligns text to the right edge. | Used for special design layouts or right-to-left languages. |
justify | Distributes text evenly between margins. | Used in documents or paragraphs for clean edges. |
Example: Centering Text in a Div
<div style="text-align: center;">
<h1>Welcome to My Website</h1>
<p>This paragraph is centered horizontally within its container.</p>
</div>
All inline content within the <div> — such as text and inline images — will be horizontally centered.
Example: Using an External CSS Rule
div.container {
text-align: center;
border: 2px dashed #999;
padding: 20px;
}
By applying this rule, any text or inline content inside elements with the 'container' class will appear centered, maintaining clean layout separation from HTML structure.
Important Notes
text-alignaffects inline content, not the container itself.- To center a block-level element (like a
<div>), usemargin: 0 auto;instead. - Combining
text-align: center;withdisplay: flex;offers even more control in modern layouts.
Practical scenario
Center a hero heading and call-to-action text on a landing page.
Common pitfalls
- Centering container instead of text, causing misalignment.
- Ignoring line wrapping and making text hard to read.
- Using
text-alignwhere alignment should be handled by layout.
Centered text can reduce readability for long paragraphs. Test with long strings and responsive widths.
Imagine a box filled with text — text-align: center; tells everything inside to stand neatly in the middle of that box.
- Use
text-align: center;to center text horizontally within a block container. - Applies to inline-level content like text and inline images.
- Combine with flexbox or grid for advanced alignment control.
<li>Does not center block-level elements themselves.