flex align-items center 不居中

flex align-items center is not centering

我有一个代码 - https://codepen.io/anon/pen/MQjpBG

这是一个简单的列表,每行有一个彩色块和文本

我需要列表是垂直的,文本和块是垂直对齐的。

我正在尝试使用 flex 和 align-items 来做到这一点,但文本和块永远不会完全居中

我是不是做错了什么,有没有更好的方法。

.element{
  display: flex;
  list-style: none;

  &__item{
    display: flex;
    align-items: center;
    margin-right: 10px;

    &:last-of-type{
      margin-right: 0;
    }

    &-square{
      background: red;
      //display: block;
      display: inline-block;
      height: 20px;
      width: 20px;
    }

    &-text{
      font-weight: bold;
    }

  }

}

我希望块和文本像这样适合。

align-items: center; 似乎做到了,但有点不对劲,就像

(在您的 codepen 中)没有将它们居中的内容。

将此添加到您的代码中:

.element{
    display: flex;
    justify-content: center; /* horizontal alignment */

.element__item {
    display: flex;           /* nested flex container */
    align-items: center;     /* vertical alignment */
}

revised codepen

要使列表垂直,只需添加 "flex-direction"

  display: flex;
  list-style: none;
  flex-direction: column;

对于水平居中对齐:

.element {
justify-content: center;
}

对于正方形和文本的垂直居中对齐:

.element__item-square {
    vertical-align: middle;
}
.element__item-text {
    vertical-align: middle;
}

不幸的是,问题似乎与所选字体有关。不同的字体将具有不同的下行高度(例如“g”的尾部)以及基线相对于完整文本框的不同定位,并且看起来某些字体将设置这些值,这样它们可能不会视觉居中。

我修改了你的 CodePen 示例,并强制将第一个元素的 font-family 设置为 Arial,同时将第二个元素保留为默认值(在 macOS 10.15/Catalina 上的 Firefox 上),Arial 版本看起来肯定更多垂直居中:

您也许可以通过更改使用的字体来解决此问题,但显然这不是一个可以在大型代码库上轻松进行的更改。