CSS Tutorial
CSS Align
Centring is one of the most common CSS tasks and one of the most confused. This guide walks through the reliable ways to centre text, blocks, and boxes both horizontally and vertically.
Centring in CSS
There is no single centre property; the right tool depends on what you are centring. Text uses text-align, a fixed-width block uses margin auto, and centring a box both ways is easiest with flexbox. Knowing which to reach for saves a lot of guesswork.
Centre text horizontally
For inline content like text or inline-block items, text-align: center on the parent centres them within the line.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: system-ui, sans-serif; padding: 16px; }
.banner {
text-align: center;
background: #e2e8f0;
padding: 20px;
}
</style>
</head>
<body>
<div class="banner">
<h3>Centred heading</h3>
<p>This text is centred with text-align: center.</p>
</div>
</body>
</html>Centre a block with margin auto
A block element with a set width can be centred horizontally by setting its left and right margins to auto. The browser splits the leftover space equally on both sides.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: system-ui, sans-serif; padding: 16px; }
.card {
width: 200px;
margin: 0 auto; /* auto left/right centres it */
background: #2563eb;
color: white;
padding: 16px;
text-align: center;
}
</style>
</head>
<body>
<div class="card">Centred block (margin: 0 auto)</div>
</body>
</html>Centre both ways with flexbox
Flexbox is the cleanest way to centre a box horizontally and vertically at once. justify-content centres along the main axis and align-items centres along the cross axis.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: system-ui, sans-serif; margin: 0; }
.stage {
display: flex;
justify-content: center; /* horizontal */
align-items: center; /* vertical */
height: 220px;
background: #f1f5f9;
}
.dot {
background: #dc2626;
color: white;
padding: 24px;
border-radius: 12px;
}
</style>
</head>
<body>
<div class="stage">
<div class="dot">Perfectly centred</div>
</div>
</body>
</html>| Goal | Best technique |
|---|---|
| Centre text | text-align: center on the parent |
| Centre a fixed-width block horizontally | margin: 0 auto |
| Centre a box both ways | display: flex + justify-content + align-items |
| Centre an absolute element | top:50%; left:50%; transform: translate(-50%, -50%) |
margin: auto only centres horizontally and only when the element has a defined width. For vertical centring, reach for flexbox or grid.
Key points
- text-align: center centres inline content like text and inline-block items.
- margin: 0 auto centres a fixed-width block horizontally.
- Flexbox with justify-content and align-items centres a box both ways.
- translate(-50%, -50%) centres an absolutely positioned element of unknown size.
