Whisher
Whisher

Reputation: 32766

justify-content works differently in Flex and Grid layouts

I'm wondering why using justify-content

the grid item takes the whole space

available instead of that used in the grid.

With justify-content: https://codepen.io/whisher/pen/JOpYdp

Without: https://codepen.io/whisher/pen/pdajjb

.wrapper {
  background-color: red;
  width: 500px;
  height: 400px;
  border: 2px solid #CCC;
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(4, 80px);
  grid-template-rows: repeat(3,100px);
  align-content: space-around;
  justify-content: space-between;
}

I mean I expect like the same of using flex

https://codepen.io/whisher/pen/YEewaW

Upvotes: 2

Views: 5775

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 371779

In flex layout, the justify-content property distributes free space in the container between or around flex items (depending on the value).

8.2. Axis Alignment: the justify-content property

The justify-content property aligns flex items along the main axis of the current line of the flex container. ... Typically it helps distribute extra free space leftover when either all the flex items on a line are inflexible, or are flexible but have reached their maximum size.

In grid layout, the justify-content property distributes free space in the container between or around grid columns (depending on the value).

Note the difference with flex: Here, justify-content aligns grid columns, not grid items.

10.5. Aligning the Grid: the justify-content and align-content properties

If the grid’s outer edges do not correspond to the grid container’s content edges (for example, if no columns are flex-sized), the grid tracks are aligned within the content box according to the justify-content and align-content properties on the grid container.

Here are the grid column tracks in your layout...

...without justify-content: space-between:

enter image description here

...and with justify-content: space-between:

enter image description here

Here's a related post that may help with further understanding:

Upvotes: 6

Related Questions