0
0
CssHow-ToBeginner · 3 min read

How to Use justify-items in CSS Grid for Aligning Items

Use the justify-items property on a CSS grid container to align all grid items horizontally inside their grid cells. Values like start, end, center, and stretch control the horizontal alignment of items within each cell.
📐

Syntax

The justify-items property sets the horizontal alignment of grid items inside their grid cells. It is applied to the grid container.

  • start: Align items to the left edge of the cell.
  • end: Align items to the right edge of the cell.
  • center: Center items horizontally in the cell.
  • stretch: Stretch items to fill the entire width of the cell (default).
css
.grid-container {
  display: grid;
  justify-items: center; /* Align items horizontally to center */
}
💻

Example

This example shows a grid with three items. The justify-items property centers all items horizontally inside their cells.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>justify-items Example</title>
<style>
  .grid-container {
    display: grid;
    grid-template-columns: repeat(3, 100px);
    grid-gap: 10px;
    justify-items: center;
    border: 2px solid #333;
    padding: 10px;
  }
  .grid-item {
    background-color: #4CAF50;
    color: white;
    padding: 20px;
    font-size: 1rem;
  }
</style>
</head>
<body>
  <div class="grid-container">
    <div class="grid-item">Item 1</div>
    <div class="grid-item">Item 2</div>
    <div class="grid-item">Item 3</div>
  </div>
</body>
</html>
Output
A horizontal row of three green boxes labeled 'Item 1', 'Item 2', and 'Item 3', each centered horizontally inside their 100px wide grid cells with space between them.
⚠️

Common Pitfalls

One common mistake is trying to use justify-items on non-grid containers or expecting it to align the entire grid container itself. It only affects items inside grid cells horizontally.

Also, justify-items does not affect vertical alignment; use align-items for that.

css
/* Wrong: applying justify-items on a flex container does nothing */
.flex-container {
  display: flex;
  justify-items: center; /* Has no effect in flexbox */
}

/* Right: apply justify-items on a grid container */
.grid-container {
  display: grid;
  justify-items: center;
}
📊

Quick Reference

  • start: Align items to the left inside each cell.
  • end: Align items to the right inside each cell.
  • center: Center items horizontally inside each cell.
  • stretch: Stretch items to fill the cell width (default).

Key Takeaways

Use justify-items on a grid container to control horizontal alignment of all grid items inside their cells.
Common values are start, end, center, and stretch.
justify-items only works with CSS Grid, not Flexbox.
It aligns items inside cells horizontally; use align-items for vertical alignment.
Default value is stretch, which makes items fill the cell width.