iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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…UseWhere
Align text inside an elementtext-alignBlock parent (e.g. p, div).
Centre a block element horizontallymargin: 0 autoOn the block itself (needs an explicit width).
Centre flex items along the main axisjustify-contentOn the flex container.
Centre flex items along the cross axisalign-itemsOn the flex container.
Override a single flex item's cross alignmentalign-selfOn the flex item.
Centre everything inside a grid cellplace-items: centerOn the grid container.
Vertically align table-cell contentvertical-alignOn 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 &raquo;</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; }

Test yourself

Q1. Which property centres text inside a paragraph?
Q2. What does `place-items: center` do on a grid container?
Q3. Which is the typical way to horizontally centre a block element with a known width?

Discussion

Loading…