在 IE11 中,Flexbox 的居中子项被填充强制放在一边

Centred child of flexbox forced aside by padding in IE11

为了将 <a> 标签集中放置在 <div> 中并让它完全填充父级,我在下面的代码片段中使用了标记和 CSS:

.container {
    align-items: center;
    background: lightcoral;
    border: 1px solid black;
    display: flex;
    height: 100px;
    justify-content: center;
    overflow: hidden;
    width: 100px;
}

.contained {
    background: lightblue;
    padding: 100px;
}
<body>
    <div class="container">
        <a class="contained" href="#">1</a>
    </div>
    <div class="container">
        <a class="contained" href="#">2</a>
    </div>
    <div class="container">
        <a class="contained" href="#">3</a>
    </div>
</body>

出于演示目的,<div>s 具有固定大小,但最终它们可能会在不同的视口大小下略微改变大小,因此为 <a> 标签提供了大量的填充以确保它们始终覆盖整个 <div>,同时保持中心位置。颜色也只是为了更容易看到效果。

在 Chrome 或 Firefox(撰写本文时分别为 58.0.3029.110 [64 位] 版和 53.0 [64 位] 版)中查看时,<a> 标签位于中央,父级 <div> 隐藏了多余的填充(您应该看不到红色,只能看到蓝色)。然而,在 IE11 中,<a> 标签被它们的填充推到右边,这与在 Chrome 和 Firefox 中看到的行为不匹配。此外,将 flex-direction: column 添加到 .container class 会导致 <a> 标签被推 down 而不是 right ,这表明问题与 flex-direction.

有关

是否有 IE 的解决方法使其与 Chrome 和 Firefox 的行为相同?

我想它会对你有所帮助

无需添加 padding 的拥抱值,您可以使用 flex 获得相同的值,您可以在 IE 中检查它是否工作正常以及您的 parent background: lightcoral;现在隐藏了。

我在这里附上了 IE 屏幕截图,它工作正常。

使用flex获取

.container {
  align-items: center;
  background: lightcoral;
  border: 1px solid black;
  display: flex;
  height: 100px;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  width: 100px;
}

.contained {
  background: lightblue;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  align-self: center;
}
<div class="container">
  <a class="contained" href="#">1</a>
</div>
<div class="container">
  <a class="contained" href="#">2</a>
</div>
<div class="container">
  <a class="contained" href="#">3</a>
</div>

为了让锚点填充父级,您只需添加 flex-grow:1,使用 flex 使其内容居中:

.container {
    align-items: center;
    background: lightcoral;
    border: 1px solid black;
    display: flex;
    flex-direction: column;   /* add this so your grow will make it grow to 100% height */
    height: 100px;
    width: 100px;
}

.contained {
    background: lightblue;
    flex-grow: 1;           /* add this for 100% height */
    align-self: stretch;    /* add this for 100% width */
    
    display:flex;           /* the following is for centring your anchor content */
    justify-content: center;
    align-items: center;
}
<body>
    <div class="container">
        <a class="contained" href="#">1</a>
    </div>
    <div class="container">
        <a class="contained" href="#">2</a>
    </div>
    <div class="container">
        <a class="contained" href="#">3</a>
    </div>
</body>