Flexbox自动边距不适用于IE中的justify-content:center

ztf*_*ter 9 html css css3 flexbox internet-explorer-11

我有一个表格,其中一个单元格可以包含许多图标,以及文本.如果存在图标,则它们显示在文本的左侧.有几种可能的对齐情况:

  1. 仅存在图标:图标应居中
  2. 仅存在文本:文本应保持对齐
  3. 图标和文本都存在:图标和文本都应该左对齐

我认为通过使用flexbox包装表格单元格中的所有内容,使用justify-content: center;然后应用于margin-right: auto;文本div ,我可以完成此操作以及其他更复杂的对齐.

如果有文本,自动边距会将所有内容推到左侧.

如果没有,justify-content样式将使图标居中.

这是一个包含我的方法的codepen.

.flexbox {
  display: flex;
  flex-direction: row;
  justify-content: center;
  border: 2px solid black;
  width: 300px;
  height: 17px;
}
.icon {
  height: 17px;
  width: 17px;
  background-color: red;
}
.text {
  margin-right: auto;
}
Run Code Online (Sandbox Code Playgroud)
<div class="flexbox">
  <div class="icon"></div>
  <div class="text">asdf</div>
</div>
Run Code Online (Sandbox Code Playgroud)

这种方法适用于Chrome,但在IE 11中没有正确应用正确的自动边距.我想知道为什么,以及我如何解决它.

额外的信息

似乎IE 11首先计算自动边距,然后对齐柔性项目而不考虑这些边距,最后尽可能地应用边距.

我相信这是因为,当justify-content: flex-end;在flexbox和文本div上设置时margin-left: auto;,图标在flexbox中右对齐,而文本被推到flexbox的边界之外几乎整个flexbox的宽度(关于什么是auto保证金应该是).

Mic*_*l_B 10

flexbox规范中所述:

在通过justify-content和进行对齐之前align-self,任何正的自由空间都分布到auto该维度的边距.

换句话说,auto保证金优先于justify-content.

在您的示例中,Chrome似乎符合规范.(Firefox,以及.)

但IE11 - 在父母拥有的情况下justify-content- 忽略margin-right: auto了flex项目.这似乎是一个错误.

何时justify-content删除,auto边距有效.

一种解决方法是justify-content完全删除并完全依赖auto边距:

  1. 仅存在图标:图标应居中
.icon { margin: 0 auto; }
Run Code Online (Sandbox Code Playgroud)

.flexbox {
  display: flex;
  flex-direction: row;
  border: 2px solid black;
  width: 300px;
  height: 17px;
}
.icon {
  height: 17px;
  width: 17px;
  background-color: red;
}
.icon {
  margin: 0 auto;
}
Run Code Online (Sandbox Code Playgroud)
<div class="flexbox">
  <div class="icon"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

  1. 仅存在文本:文本应左对齐
.text { margin-right: auto; }
Run Code Online (Sandbox Code Playgroud)

.flexbox {
  display: flex;
  flex-direction: row;
  border: 2px solid black;
  width: 300px;
  height: 17px;
}
.icon {
  height: 17px;
  width: 17px;
  background-color: red;
}
.text {
  margin-right: auto;
}
Run Code Online (Sandbox Code Playgroud)
<div class="flexbox">
  <div class="text">asdf</div>
</div>
Run Code Online (Sandbox Code Playgroud)

  1. 图标和文本都存在:图标和文本都应该左对齐
.text { margin-right: auto; }
Run Code Online (Sandbox Code Playgroud)

.flexbox {
  display: flex;
  flex-direction: row;
  border: 2px solid black;
  width: 300px;
  height: 17px;
}
.icon {
  height: 17px;
  width: 17px;
  background-color: red;
}
.text {
  margin-right: auto;
}
Run Code Online (Sandbox Code Playgroud)
<div class="flexbox">
  <div class="icon"></div>
  <div class="text">asdf</div>
</div>
Run Code Online (Sandbox Code Playgroud)