【问题标题】:Making a flex item float right使弹性项目向右浮动
【发布时间】:2016-07-11 00:10:46
【问题描述】:

我有一个

<div class="parent">
    <div class="child" style="float:right"> Ignore parent? </div>
    <div> another child </div>
</div>

父母有

.parent {
    display: flex;
}

对于我的第一个孩子,我只想将项目向右浮动。

和我的其他 div 遵循父级设置的 flex 规则。

这可能吗?

如果没有,我该如何在flex下做float: right

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    您不能在 flex 容器 中使用 float,原因是 float 属性不适用于 flex-level 框,如您在此处看到的 @987654321 @。

    因此,如果您想将 child 元素定位到 parent 元素的右侧,您可以使用 margin-left: auto 但现在 child 元素也会将其他 div 推到右侧,如您在此处看到的 Fiddle .

    你现在可以做的是改变元素的顺序并在child元素上设置order: 2,这样它就不会影响第二个div

    .parent {
      display: flex;
    }
    .child {
      margin-left: auto;
      order: 2;
    }
    <div class="parent">
      <div class="child">Ignore parent?</div>
      <div>another child</div>
    </div>

    【讨论】:

    • 谢谢,我可以看看第一个解决方案。我不想使用 display:absolute,因为我的其他孩子不应该包含在第一个孩子之下。
    • "浮动不会侵入弹性容器"。这是真的,但这不是原因。原因是float 属性不适用于弹性级别的盒子。
    • 这行得通,谢谢!为什么justify-self: end;(或类似的东西)对孩子不起作用?对于 flexbox 问题,这似乎不是那么灵活的解决方案。
    • @BradyDowling 我知道这是一个迟到的回复,但 justify-self end 需要将显示设置为网格。 Flexbox 将忽略 justify-self:end。见这里:developer.mozilla.org/en-US/docs/Web/CSS/justify-self
    • another child
      Ignore parent?
      你可以交换两个 div 并且没有顺序 2 它也可以工作
    【解决方案2】:

    你不需要花车。事实上,它们没用,因为floats are ignored in flexbox

    您也不需要 CSS 定位。

    有几种 flex 方法可用。 auto margins 已在 another answer 中提及。

    这里有另外两个选项:

    • 使用justify-content: space-betweenorder 属性。
    • 使用 justify-content: space-between 并颠倒 div 的顺序。

    .parent {
        display: flex;
        justify-content: space-between;
    }
    
    .parent:first-of-type > div:last-child { order: -1; }
    
    p { background-color: #ddd;}
    <p>Method 1: Use <code>justify-content: space-between</code> and <code>order-1</code></p>
    
    <div class="parent">
        <div class="child" style="float:right"> Ignore parent? </div>
        <div>another child </div>
    </div>
    
    <hr>
    
    <p>Method 2: Use <code>justify-content: space-between</code> and reverse the order of 
                 divs in the mark-up</p>
    
    <div class="parent">
        <div>another child </div>
        <div class="child" style="float:right"> Ignore parent? </div>
    </div>

    【讨论】:

      【解决方案3】:

      在父级中使用justify-content: flex-end;

      display: flex;
      width: 100%;
      flex-wrap: wrap;
      justify-content: flex-end;
      

      more info

      【讨论】:

        猜你喜欢
        • 2017-06-18
        • 1970-01-01
        • 2017-11-22
        • 1970-01-01
        • 1970-01-01
        • 2018-07-19
        • 2015-08-12
        • 1970-01-01
        • 2014-04-21
        相关资源
        最近更新 更多