Alexander Solonik Alexander Solonik - 4 years ago 214
HTML Question

align-items:center; not working as intended

I was just reading David's article HERE and decided to give flexbox a try and so i made the following example of my own:

<div class="wrpr">

<div></div>
<div></div>
<div></div>
<div></div>

</div>


CSS

.wrpr {
display: flex;
border: 5px solid tomato;
height: 300px;
align-items:center;
flex-wrap:wrap;
}

.wrpr div {
background: #eee;
height: 50px;
width: 49%;
margin: 0 .5%;
}

.wrpr div:nth-child(odd) {
background: #727272;
}


FIDDLE HERE

Now the annoying part is that the 4 div's are not exactly centered, but rather spaced out. why is that happening?

i believe this is a typical newbie problem, for someone migrating to flexbox, but i really can't find a solution to this issue.

can anybody help me understand why
align-items:center;
isn't working as intended?

Answer Source

You need to use align-content to control multi-line spacing. align-items is for single-line use only. Add one line to your code:

.wrpr {
  display: flex;
  border: 5px solid tomato;
  height: 300px;
  align-items: center;
  align-content: center; /* new */
  flex-wrap: wrap;
}

DEMO

align-content

The align-content property aligns a flex container’s lines within the flex container when there is extra space in the cross-axis, similar to how justify-content aligns individual items within the main-axis. Note, this property has no effect on a single-line flex container. (emphasis mine)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download