使弹性项向右浮动

我有一个

<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

235381 次浏览

You can't use float inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle.

So if you want to position child element to right of parent element you can use margin-left: auto but now child element will also push other div to the right as you can see here Fiddle.

What you can do now is change order of elements and set order: 2 on child element so it doesn't affect second div

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

You don't need floats. In fact, they're useless because floats are ignored in flexbox.

You also don't need CSS positioning.

There are several flex methods available. auto margins have been mentioned in another answer.

Here are two other options:

  • Use justify-content: space-between and the order property.
  • Use justify-content: space-between and reverse the order of the divs.

.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>

Use justify-content: flex-end; in parent:

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

more info