【问题标题】:Flex item not centering in IEFlex 项目不在 IE 中居中
【发布时间】:2019-11-04 00:49:59
【问题描述】:

我正在尝试在两个轴上的页面中心放置一个小框。我让它在 Chrome、Firefox 和 Edge 中运行,但 IE 仍然无法对齐。与我的内容相比,该框似乎卡在了一个虚拟框的右下角。

我尝试更改 .content 的 flex 属性并将其包装到另一个 <div /> 但无济于事。

如何让框在 IE 中居中?

html, body {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.content {
  position: absolute;
  width: 400px;
  height: 200px;
  background-color: #333333;
}
<div class="content">

【问题讨论】:

  • IE11?因为正如Can i use 所说:部分支持是由于存在大量错误
  • 是的,IE11。我想知道是否有任何解决方法。
  • 尝试添加到您的.content margin: auto
  • 我在 SO 上找到了这个answer,也许它可以帮助你

标签: html css internet-explorer flexbox internet-explorer-11


【解决方案1】:

问题

flex 容器的绝对定位子元素会从文档的正常流程中移除。

事实上,它们甚至不是弹性项目,因为它们不接受弹性属性。

来自规范:

§ 4.1. Absolutely-positioned Flex Children

由于它是外流的,因此是 flex 的绝对定位子代 容器不参与弹性布局。

这就是为什么您的布局在 Chrome、Firefox 和 Edge 中都能正常工作的原因:

继续规范:

确定 flex 容器的绝对定位子项的静态位置,以使子项被定位为好像它是 flex 容器中唯一的 flex 项,假设子项和 flex 容器都是固定大小的盒子他们使用的大小。为此,auto 边距被视为零。

read more >>

但是,IE11 provides only partial supportcurrent flexbox specification,这可能解释了渲染差异。

解决方案

由于您的内容项没有做任何与 flex 相关的事情,只需使用标准的非 flex 方法进行水平和垂直居中。

body {
  height: 100vh;
  position: relative;
}

.content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  height: 200px;
  background-color: #333333;
}
<div class="content">

上面的居中方法在这里解释一下:

【讨论】:

    【解决方案2】:

    尝试删除位置属性。代码如下:

    html, body {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .content {
      width: 400px;
      height: 200px;
      background-color: #333333;
    }
    

    IE浏览器中的结果如下:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      • 2021-09-09
      • 2021-10-29
      • 1970-01-01
      • 2017-07-27
      • 2018-07-19
      • 1970-01-01
      相关资源
      最近更新 更多