This page covers CSS alignment: text-align, vertical-align, and centering
block elements with margin: auto. Each example shows output and code.
text-align — horizontal text alignmentUse text-align on block elements to align inline content (text, inline images) within
that block. Values: left, center, right, justify.
text-align: left (default)
text-align: center
text-align: right
text-align: justify — stretches lines so both edges align. Good for columns.
p { text-align: left; } /* default */
p { text-align: center; }
p { text-align: right; }
p { text-align: justify; }
text-align affects inline content (text, <span>,
<img>) inside the block. It does not center block elements themselves.
justify stretches lines so both edges align; can create awkward gaps on short lines.
vertical-align — inline/inline-block alignmentUse vertical-align on inline or inline-block elements
to align them vertically within a line. It does not center block elements or text in a box.
<span class="box" style="vertical-align: baseline;">baseline</span>
<span class="box" style="vertical-align: top;">top</span>
<span class="box" style="vertical-align: middle;">middle</span>
<span class="box" style="vertical-align: bottom;">bottom</span>
baseline (default) aligns with the text baseline. top =
top of line box; middle = middle of line box; bottom = bottom of line box. Also:
sub, super, and length values like 2px, 0.5em. Works on
inline and inline-block only.
margin: autoTo horizontally center a block element, give it a width (or max-width) and
margin-left: auto; margin-right: auto; (or shorthand margin: 0 auto;). The auto margins
take up the remaining space on each side.
.box {
width: 200px;
margin: 0 auto;
}
width (or
max-width) and margin-left: auto; margin-right: auto; lets the browser split the
leftover space evenly on left and right, centering the element. margin: 0 auto = top/bottom 0,
left/right auto.
line-heightFor a single line of text inside a box, set line-height equal to the box height. The
text is vertically centered.
.box {
height: 60px;
line-height: 60px;
text-align: center;
}
line-height equals the container height, a single line of text
sits in the middle vertically. Only works for one line. For multiple lines or complex layouts, use Flexbox
(align-items: center) or Grid.
text-align: left, center, right, justify — aligns inline content in a block.vertical-align: baseline, top, middle, bottom — aligns inline/inline-block in a line.margin: 0 auto + fixed width — horizontally centers a block element.line-height = height — simple vertical centering for one line of text.