我可以在flexbox中拉物品吗? [英] Can I pull items in flexbox?
问题描述
我需要创建以下结构:
| |
| [项目] [项目] [项目] [项目] [项目] |
| |
里面有5个物品。它们都垂直居中对齐。第三个元素向左拉,最后两个元素向右拉。
我知道我可以使用浮点数,但是它有很多缺点,包括麻烦
我决定使用flexbox,事实证明它更加方便和灵活。另外,它更加易于响应。
现在我的问题是,我可以在flexbox中分发这样的元素吗?理想情况下,这5个元素中的每个元素都是flexbox项。但是我怎样才能告诉flexbox将那3个拖到左边,把那2个拖到右边呢?我认为添加空元素来填充空间不是最好的主意。
这是可行的还是我需要这样做?
| |
| [项目] [项目] |
| |
每个项目在哪里包含所需元素,甚至可能是单独的flexbox?
使用 display:flex
和 margin-left:auto
表示第四个 子元素
< main>
< div>项目1< / div>
< div>项目2< / div>
< div>项目3< / div>
< div>项目4< / div>
< div>项目5< / div>
< / main>
Css
main {
display:flex;
}
div {
宽度:12%;
保证金:0 10px;
边框:1px红色实心;
}
div:nth-child(4){
margin-left:auto;
}
Codepen :
I need to create a following structure:
| |
| [item][item][item] [item][item]|
| |
There are 5 items inside. They are all vertically aligned to the middle. 3 first elements are pulled to the left and 2 last elements are pulled to the right.
I know I can use floats for it, but it has several drawbacks, including troublesome vertical aligning.
I decided to use flexbox, which turns out to be a lot more convenient and flexible. Plus, it's more responsive-friendly.
Now my question is, can I distribute my elements like this in flexbox? Ideally, each of those 5 elements would be flexbox item. But how can I tell flexbox to pull those 3 to the left and those 2 to the right? I think adding empty element to fill space is not the best idea.
Is this doable or do I need to do it like this?
| |
| [ item ] [ item ]|
| |
Where each item would contain needed elements inside, or perhaps even be separate flexboxes?
Use display: flex
along with margin-left: auto
for the 4th child element
<main>
<div>item 1</div>
<div>item 2</div>
<div>item 3</div>
<div>item 4</div>
<div>item 5</div>
</main>
Css
main {
display: flex;
}
div {
width: 12%;
margin: 0 10px;
border: 1px red solid;
}
div:nth-child(4) {
margin-left: auto;
}
Codepen: http://codepen.io/anon/pen/wKvMOw
Output:
这篇关于我可以在flexbox中拉物品吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!