CSS Text Alignment
Text alignment is the way text sits across the space inside a block. The text-align property sets that alignment.
Centre the heading
The value center puts the heading text in the middle of its block.
h1 {
text-align: center;
}Align the box text right
The selector targets the paragraph inside the box. Its text moves to the right edge.
.box p {
text-align: right;
}Indent the first line
The text-indent property moves the first line of a paragraph. The other lines stay where they were.
p {
text-indent: 30px;
}Example
h1 {
text-align: center;
}
.intro {
text-align: center;
}
.box p {
text-align: right;
}
p {
text-indent: 30px;
}
#demo {
text-align: center;
}Key points
- The values left, right and center place text at the left, at the right or in the middle.
- The value justify stretches lines so they reach both edges.
- Alignment passes from a block down to the text inside it.
- A block stays in place when its text is aligned.
- Text alignment applies to the contents of a block, not to the block itself.
In this example, the heading text is centred. The intro paragraph is centred as well. The paragraph inside the box is aligned to the right. Every paragraph gets a first-line indent of 30 pixels. The demo paragraph is centred.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which property centres text inside a block?