extra space when centering elements using flexbox

align-content

Note that align-content: stretch is also in play here.

The align-content property distributes free space among flex lines. It's default value is stretch.

So when your items wrap to two lines, align-content: stretch distributes free space equally across lines.


align-items

Remove align-items: center from the container. You'll then notice that when items wrap, there is no gap between lines (or "rows", in this case). demo

Line heights are set by align-content, the height of the items, and the content of the items.

enter image description here


align-content and align-items working together

Restore align-items: center. Now when items wrap, there is a visible gap between lines.

enter image description here

This is because align-items: center positions the items in the vertical center of the line, based on line heights established by align-content: stretch, item heights, and item content.

The line heights are set here (with align-content: stretch and align-items: stretch):

enter image description here

... and continue here (with align-content: stretch and align-items: center):

enter image description here

align-items is having no effect on the height of the flex line. That job is andled by align-content.

However, by changing the value of align-content (to flex-start, flex-end, space-between, center, etc.), you pack the flex lines, squeezing out the free space, and hence removing the gaps.

enter image description here


Why is the first row taller than the second row with align-content: stretch?

The container is set to height: 800px.

There are two items with defined heights:

  • .item-3 { height: 250px }
  • .item-4 { height: 300px }

When .item-5 and .item-6 form the second row, the free space in the container is, in its simplest form, 500px (800px - 300px).

So, in a container with two rows and align-content: stretch, 250px is distributed to the height of each row.

  • first row is 300px (defined height) plus 250px (free space)
  • second row is 250px (free space)

That's why the first row is taller.

Just note that the free space calculation above is slightly off in the actual layout. That's because there is text in the items, which consumes free space. You can factor in the height of the text to get the precise figures, or remove the text altogether to see the calculations above fall into place.


More details:

  • How does flex-wrap work with align-self, align-items and align-content?
  • Equal height rows in a flex container

Tags:

Html

Css

Flexbox