trevorhinesley trevorhinesley - 7 months ago 27
HTML Question

Flexbox - justify-content: center and align-items: center not working?

I have a pretty basic flex setup and, for whatever reason, the div in question won't vertically center inside its parent tag. You can see the isolated test case below.



.likeness-rank-table {
border-radius: 3px;
margin-bottom: 20px;
display: block;
}
.likeness-rank-table .col {
box-sizing: border-box;
text-align: center;
position: relative;
flex: 1;
max-width: 20%;
min-height: 50px;
display: flex;
flex-wrap: wrap;
}
.likeness-rank-table .col .col-inner {
flex: 1;
align-items: center;
justify-content: center;
height: 150px;
}
.likeness-rank-table .likeness-rank-table-body {
display: flex;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border: 1px solid #a2a5a7;
}
.draggable-tags .draggable-tag {
display: inline-block;
float: left;
width: 20%;
margin-bottom: 5px;
}
.draggable-tag {
text-align: center;
padding: 0 15px;
box-sizing: border-box;
}
.draggable-tag .draggable-tag-inner {
position: relative;
padding: 10px 0;
background-color: #63b3ce;
color: #fff;
}

<div class="likeness-rank-table">
<div class="likeness-rank-table-body">
<div class="col">
<div class="col-inner droppable">
<div class="draggable-tag ui-draggable">
<div class="draggable-tag-inner">
This Blue Box Should Be Horizontally and Vertically Centered Inside The Big White Box But It's Not
</div>
</div>
</div>
</div>
</div>
</div>





Here's a codepen to see it:

http://codepen.io/trevorhinesley/pen/grQKPO

Answer

There are certain flex properties that are applicable only on flex items, while others are only applicable on flex containers.

The align-items and justify-content properties apply only to flex containers. Yet, you are using them on a flex item...

.likeness-rank-table .col .col-inner {
  flex: 1;
  align-items: center;
  justify-content: center;
  height: 150px;
}

... so they are being ignored.

You need to add display: flex to the rule above. That will get align-items: center to work.

However, justify-content: center will continue to fail because the parent has a max-width: 20% limiting horizontal movement.

.likeness-rank-table .col {
  box-sizing: border-box;
  text-align: center;
  position: relative;
  flex: 1;
  max-width: 20%;            /* limits horizontal centering of child element */
  min-height: 50px;
  display: flex;
  flex-wrap: wrap;
}

So, apply the horizontal centering to the parent another level up.

.likeness-rank-table .likeness-rank-table-body {
  display: flex;
  border-bottom-left-radius: 3px;
  border-bottom-right-radius: 3px;
  border: 1px solid #a2a5a7;
  justify-content: center;    /* new */
}

Revised Codepen

Here's a useful list of flex properties broken down by parent and child: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Comments