How to Justify Text in CSS: Simple Guide with Examples
To justify text in CSS, use the
text-align: justify; property on the element containing the text. This spreads the text evenly across the line width, aligning both left and right edges.Syntax
The CSS property to justify text is text-align. Setting it to justify aligns the text to both the left and right edges of its container, creating a clean block of text.
text-align: The property controlling horizontal alignment of inline content.justify: The value that spreads text evenly across the line width.
css
selector {
text-align: justify;
}Example
This example shows a paragraph with justified text. The text lines stretch to fill the container width, aligning both left and right edges.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Justify Text Example</title> <style> p { width: 300px; text-align: justify; border: 1px solid #ccc; padding: 10px; font-family: Arial, sans-serif; } </style> </head> <body> <p> Justifying text in CSS makes the text spread evenly across the width of the container, aligning both the left and right edges. This creates a neat block of text similar to what you see in newspapers or books. </p> </body> </html>
Output
A rectangular box with a paragraph inside where the text lines stretch evenly from left to right edges, forming a clean block of text.
Common Pitfalls
Some common mistakes when justifying text include:
- Not setting a width or max-width on the container, so the text stretches too wide and looks odd.
- Using
text-align: justify;on very short lines or headings, which can create large gaps between words. - Ignoring readability issues caused by uneven spacing, especially on narrow screens.
To fix these, always control the container width and avoid justifying very short text blocks.
css
/* Wrong: Justify on short heading */ h2 { text-align: justify; width: 200px; } /* Right: Use left align for headings */ h2 { text-align: left; width: 200px; }
Quick Reference
| Property | Value | Effect |
|---|---|---|
| text-align | justify | Aligns text to both left and right edges |
| text-align | left | Aligns text to the left edge (default) |
| text-align | right | Aligns text to the right edge |
| text-align | center | Centers the text horizontally |
Key Takeaways
Use
text-align: justify; to align text evenly on both edges.Set a container width to avoid overly stretched lines.
Avoid justifying short lines or headings to prevent awkward spacing.
Justified text works best for paragraphs, not for small text blocks.
Test on different screen sizes to maintain readability.