【问题标题】:Absolute positioned item in a flex container still gets considered as item in IE & Firefoxflex 容器中的绝对定位项仍被视为 IE 和 Firefox 中的项
【发布时间】:2015-07-07 23:36:06
【问题描述】:

如果我在 flex 容器中有多个属性为 justify-content: space-between 的元素,我想绝对定位其中一个并从 flex 流中删除,如下所示:

这在 Chrome 中有效,但在 IE 和 Firefox 中无效,因为绝对定位的元素被视为 0 宽度,但仍在 flex 流中:

是否有解决方案保持布局不变?

CodePen

【问题讨论】:

    标签: css css-position flexbox absolute


    【解决方案1】:

    我发现这些都没有处理我的情况,因为我希望三个元素均匀分布,一个绝对定位的兄弟元素。我发现在这种情况下,诀窍就是将margin-right: auto 添加到第一个要均匀分布的元素,并将margin-left: auto 添加到最后一个要均匀分布的元素。你可以在这个小提琴http://jsfiddle.net/tch6y99d/

    【讨论】:

      【解决方案2】:

      我有一个更简单的技巧来解决这个特殊问题。

      div {
        background-color: #66BB66;
        display: flex;
        position: fixed;
        width: 100%;
        justify-content: space-between;
      }
      div > img:nth-child(2) {
        position: absolute;
        left: 0;
      }
      <div>
        <img src="http://www.fillmurray.com/150/150">
        <img src="http://www.fillmurray.com/150/100">
        <img src="http://www.fillmurray.com/150/150">
      </div>

      只需更改 DOM 中的顺序。绝对定位的元素仍然定位在您放置的任何位置,尽管 flexbox 仍然将其视为在流中,但它在流中(在 dom 中)的位置导致 flexbox 在浏览器之间以相同的方式分配空间。

      我相信您可以使用 order 属性来实现相同的目的。

      【讨论】:

      • 这个在我的情况下有效,另一个解决方案没有。
      【解决方案3】:

      原来只需要三个简单的步骤

      (Demo)

      1)。将每个孩子的左右边距设置为自动

      img {
          margin-left: auto;
          margin-right: auto;
      }
      

      2)。将第一个孩子的左边距设置为0

      img:nth-child(2) {
          margin-left: 0;
      }
      

      3)。将最后一个孩子的右边距设置为0

      img:last-child {
          margin-right: 0;
      }
      

      如果您错过了这些步骤中的任何一个,它将无法正常工作

      这适用于firefox和chrome,我还没有在任何其他浏览器中测试过。

      编辑:

      感谢@Pontiacks

      显然,您可以将margin-left: auto 添加到img:nth-child(2) 中而侥幸

      updated jsfiddle

      【讨论】:

        猜你喜欢
        • 2017-11-09
        • 1970-01-01
        • 2019-08-18
        • 1970-01-01
        • 2018-02-03
        • 1970-01-01
        • 2011-01-08
        • 1970-01-01
        相关资源
        最近更新 更多