Flexbox - 在同一行左右对齐 [英] Flexbox - Justify left and right on the same line
问题描述
情况:
我在 Flexbox 中构建了一个简单的导航栏.我想将一个项目向左浮动,并将其他项目固定在右侧.
I have a simple nav bar that I'm building in Flexbox. I want to float one item to the left and keep the others pegged to the right.
示例:
<nav>
<ul class="primary-nav">
<li><a href="#" id="item1">ListItem1</a></li>
<li><a href="#" id="item2">ListItem2</a></li>
<li><a href="#" id="item3">ListItem3</a></li>
<li><a href="#" id="item4">ListItem4</a></li>
</ul>
</nav>
问题
通常答案只涉及左右浮动的项目,但据说在 Flexbox 中使用浮动是不好的.我正在考虑使用 justify-content 并使用 flex-start 和 flex-end 但这效果不太好.
Typically answers involve just floating items left and right but supposedly in Flexbox it is bad to use Floats. I was thinking about using justify-content and using flex-start and flex-end but that Isn't working out too well.
我尝试将 flex-start 应用于第一个项目,然后将 flex-end 应用于其他项目,但效果不佳.
I tried applying flex-start to the first item and then flex-end to the others but that didn't work so well.
像这样:
.primary-nav #item1 {
justify-content: flex-start;
}
.primary-nav #item2 {
justify-content: flex-end;
}
.primary-nav #item3 {
justify-content: flex-end;
}
.primary-nav #item4 {
justify-content: flex-end;
}
表扬并感谢任何拥有 Flexbox 技能并能帮助我展示处理这种情况的正确方法的人.:)
Praise and thanks to anyone who has Flexbox skills and can help show me the proper way to handle this situation. :)
推荐答案
如果您希望左侧只有一个元素而右侧有所有其他元素,最简单的解决方案是使用 justify-content:flex-end
在父元素上将所有元素向右移动,然后将 margin-right:auto
添加到您想要在左侧的元素
If you're looking to have just one element on the left and all others on the right, the simplest solution is to use justify-content:flex-end
on the parent element to move all elements to the right and then add margin-right:auto
to the element you want to have on the left
.primary-nav {
display:-webkit-flex;
display:flex;
list-style-type:none;
padding:0;
justify-content:flex-end;
}
.left {
margin-right:auto;
}
<nav>
<ul class="primary-nav">
<li class="left"><a href="#">ListItem1</a></li>
<li class="right"><a href="#">ListItem2</a></li>
<li class="right"><a href="#">ListItem3</a></li>
<li class="right"><a href="#">ListItem4</a></li>
</ul>
</nav>
这篇关于Flexbox - 在同一行左右对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!