IE 10/11 flex 子溢出对齐的解决方法

Mat*_*che 7 css flexbox internet-explorer-10 internet-explorer-11

如果 flex 容器具有 justify-content: center,并且有一个比容器宽的 flex 子元素,则内容在除 IE10 和 IE11 之外的所有浏览器中保持居中(内容在两个方向上均等溢出)。

在大多数浏览器中,您会得到:

在此处输入图片说明

在 IE 10/11 中,您会得到:

在此处输入图片说明

我需要一种方法来在那些 IE 浏览器中实现居中布局,而无需完全放弃 flexbox 方法。如有必要,我对 CSS hack IE 解决方法持开放态度。

这是示例的小提琴:

.wrap {
  width: 100%;
  height: 100%;
}

.layer {
  display: -ms-flexbox;
  display: flex;
  -ms-flex-pack: center;
  justify-content: center;
  -ms-flex-align: center;
  align-items: center;
  margin: 0 auto;
  width: 100px;
  height: 100px;
  border: 1px solid blue;
}

.layer-inner {
  font-size: 20px;
  width: auto;
  white-space: nowrap;
  line-height: 1em;
}
Run Code Online (Sandbox Code Playgroud)
<div class="wrap">
  <div class="layer">
    <span class="layer-inner">
      This overlowing text should be centered
    </span>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

Mat*_*che 5

我想到了。在 IE 10/11 中,“justify-content”和“align-items”表现不同。如果子级沿 justify-content 轴大于容器,则 IE 10/11 将只使用“justify-content: flex-start”行为。如果孩子沿着“align-items”轴大于容器,内容将根据“align-items”值正确对齐,即使孩子溢出容器。

我的解决方案只是在下面的代码段中添加“flex-direction: column”:

.wrap {
  width: 100%;
  height: 100%;
}

.layer {
  display: -ms-flexbox;
  display: flex;
  -ms-flex-direction: column;
  flex-direction: column;
  -ms-flex-pack: center;
  justify-content: center;
  -ms-flex-align: center;
  align-items: center;
  margin: 0 auto;
  width: 100px;
  height: 100px;
  border: 1px solid blue;
}

.layer-inner {
  font-size: 20px;
  width: auto;
  white-space: nowrap;
  line-height: 1em;
}
Run Code Online (Sandbox Code Playgroud)
<div class="wrap">
  <div class="layer">
    <span class="layer-inner">
      This overlowing text should be centered
    </span>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)