CSS Alignment — Demo

This page covers CSS alignment: text-align, vertical-align, and centering block elements with margin: auto. Each example shows output and code.

1. text-align — horizontal text alignment

Use text-align on block elements to align inline content (text, inline images) within that block. Values: left, center, right, justify.

Output

text-align: left (default)

text-align: center

text-align: right

text-align: justify — stretches lines so both edges align. Good for columns.

Code
p { text-align: left; }   /* default */
p { text-align: center; }
p { text-align: right; }
p { text-align: justify; }
Explanation: 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.

2. vertical-align — inline/inline-block alignment

Use 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.

Output
baseline top middle bottom
Code
<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>
Explanation: 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.

3. Centering a block element: margin: auto

To 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.

Output
Centered block (width: 200px, margin: 0 auto)
Code
.box {
  width: 200px;
  margin: 0 auto;
}
Explanation: Block elements take full width by default. Setting 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.

4. Simple vertical centering: line-height

For a single line of text inside a box, set line-height equal to the box height. The text is vertically centered.

Output
Single line: line-height = height
Code
.box {
  height: 60px;
  line-height: 60px;
  text-align: center;
}
Explanation: When 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.

5. Quick summary