Html 使弹性项目向右浮动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36182635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Making a flex item float right
提问by Zhen Liu
I have a
我有一个
<div class="parent">
<div class="child" style="float:right"> Ignore parent? </div>
<div> another child </div>
</div>
The parent has
家长有
.parent {
display: flex;
}
For my first child, I want to simply float the item to the right.
对于我的第一个孩子,我只想将项目向右浮动。
And my other divs to follow the flex rule set by the parent.
我的其他 div 遵循父级设置的 flex 规则。
Is this something possible?
这是可能的吗?
If not, how do I do a float: right
under flex?
如果没有,我该如何做一个float: right
under flex?
回答by Nenad Vracar
You can't use float
inside flex containerand the reason is that float property does not apply to flex-level boxesas you can see here Fiddle
.
您不能float
在flex 容器内使用,原因是float 属性不适用于 flex-level 框,如您所见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
.
因此,如果您想将child
元素定位到元素的右侧,parent
您可以使用,margin-left: auto
但现在child
元素也会将其他元素推div
到右侧,如您所见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
你现在可以做的是改变元素的顺序并order: 2
在child
元素上设置,这样它就不会影响第二个 div
.parent {
display: flex;
}
.child {
margin-left: auto;
order: 2;
}
<div class="parent">
<div class="child">Ignore parent?</div>
<div>another child</div>
</div>
回答by Michael Benjamin
You don't need floats. In fact, they're useless because floats are ignored in flexbox.
你不需要浮动。事实上,它们是无用的,因为浮动在 flexbox 中被忽略了。
You also don't need CSS positioning.
您也不需要 CSS 定位。
There are several flex methods available. auto
marginshave been mentioned in another answer.
有几种 flex 方法可用。在另一个答案中提到了auto
边距。
Here are two other options:
这是另外两个选项:
- Use
justify-content: space-between
and theorder
property. - Use
justify-content: space-between
and reverse the order of the divs.
- 使用
justify-content: space-between
和order
财产。 - 使用
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>