pjk_ok
pjk_ok

Reputation: 967

justify-items not working in CSS Grid

I've a CSS Grid, and I'm trying to set the justify-items property to start.

This (or any of the other properties relating to it) aren't working and in my text editor (atom) it is showing as grayed out which usually means an error.

I've looked at the specification and this property is definitely part of the spec and have even found a video tutorial of it working.

When I use it though it doesn't work and I can't get my head around why.

When I have copied the code to codepen it still does not work.

The codepen here: https://codepen.io/emilychews/pen/EvLPgJ

.gridwrapper {
  background: #e6e6e6;
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  grid-auto-rows: 100px;
  grid-row-gap: 10px;
  grid-column-gap: 10px;
  justify-items: start; /* THIS LINE ISN'T WORKING */
  align-items: stretch;
}

.gridwrapper div:nth-child(1) {
  grid-column: 1 / 4;
}

.gridwrapper div:nth-child(6) {
  grid-column: 1 / 3;
}

.gridwrapper div {
  padding: 1em;
  background: red;
  border: white;
  width: 100%;
  color: white;
  box-sizing: border-box;
}

.gridwrapper div:nth-child(odd) {
  background: blue;
}
<div class="gridwrapper">
  <div class="grid double-col double-row">1</div>
  <div class="grid">2</div>
  <div class="grid">3</div>
  <div class="grid">4</div>
  <div class="grid">5</div>
  <div class="grid">6</div>
  <div class="grid">7</div>
  <div class="grid">8</div>
</div>

Upvotes: 13

Views: 24988

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 371779

The justify-items property aligns grid items by distributing free space in the columns (not the overall container).

In this case, however, there is no free space because each item occupies the full width of the column.

.gridwrapper div { width: 100% }

When you remove that rule, justify-items works.

Here's a more complete explanation:

revised codepen

.gridwrapper {
  background: #e6e6e6;
  display: grid;
  grid-template-columns: repeat(8, 25px); /* adjustment; otherwise 1fr... */ 
  grid-auto-rows: 100px;                  /* all free space */
  grid-row-gap: 10px;
  grid-column-gap: 10px;
  justify-content: end; /* adjustment */
  align-items: stretch;
}

.gridwrapper div:nth-child(1) {
  grid-column: 1 / 4;
}

.gridwrapper div:nth-child(6) {
  grid-column: 1 / 3;
}

.gridwrapper div {
  padding: 1em;
  background: red;
  border: white;
  /* width: 100%; */
  color: white;
  box-sizing: border-box;
}

.gridwrapper div:nth-child(odd) {
  background: blue;
}
<div class="gridwrapper">
  <div class="grid double-col double-row">1</div>
  <div class="grid">2</div>
  <div class="grid">3</div>
  <div class="grid">4</div>
  <div class="grid">5</div>
  <div class="grid">6</div>
  <div class="grid">7</div>
  <div class="grid">8</div>
</div>

Upvotes: 11

Related Questions