CSS Align
CSS has several ways to align content. The right one depends on whether you're aligning text, a block, a flex item, or a grid item.
Pick by context
| You want to… | Use | Where |
|---|---|---|
| Align text inside an element | text-align | Block parent (e.g. p, div). |
| Centre a block element horizontally | margin: 0 auto | On the block itself (needs an explicit width). |
| Centre flex items along the main axis | justify-content | On the flex container. |
| Centre flex items along the cross axis | align-items | On the flex container. |
| Override a single flex item's cross alignment | align-self | On the flex item. |
| Centre everything inside a grid cell | place-items: center | On the grid container. |
| Vertically align table-cell content | vertical-align | On the cell. |
The dead-simple centring recipe
CSS
.parent {
display: grid;
place-items: center; /* centres any child horizontally + vertically */
min-height: 100vh;
}
Tip: "How do I centre a div" used to be a meme. With
place-items: center on a grid (or justify-content + align-items on flex), it's now two lines.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Align</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Centre any single child both horizontally and vertically in one line.
.parent { display: grid;
-items: center; min-height: 100vh; }
A shorthand of justify- and align-.
Discussion
Loading…