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

前端 未结 2 1262
孤城傲影
孤城傲影 2021-01-23 02:27

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.

相关标签:
2条回答
  • 2021-01-23 02:42

    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/

    0 讨论(0)
  • 2021-01-23 03:02

    You need to @include flex on your col-inner (line 40 of your scss), as align-items and justify-content only work on the flexbox element (see this handy guide).

    Then to align the .col element within the big white box you can add justify-content: center to .likeness-rank-table-body on line 47 of your scss.

    0 讨论(0)
提交回复
热议问题