Html CSS3 Flex:将孩子拉到右边
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19564287/
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
CSS3 Flex: Pull child to the right
提问by Macks
here's what I have Fiddle
这是我的 小提琴
ul {
display: flex;
justify-content: flex-start;
flex-direction: row;
align-items: center;
width: 100%;
height: 100px;
background: #333;
padding: 15px;
}
ul li {
padding: 15px;
margin: 5px;
background: #efefef;
border: 1px solid #ccc;
display: inline-block;
list-style: none;
}
#item-1 {
height: 50px;
}
#item-2 {
height: 70px;
}
<ul>
<li id="item-1">Home</li>
<li id="item-2">Menu</li>
<li>More</li>
<li>Stuff</li>
<li>Settings</li>
</ul>
I want the last item inside the flex-box to be pulled to the right("Settings" in my fiddle) while keeping all other items the way they are. The "Settings"-item should also be centered vertically and everything.
我希望 flex-box 中的最后一个项目被拉到右边(我的小提琴中的“设置”),同时保持所有其他项目的原样。“设置”项目也应该垂直居中和一切。
align-self: flex-end
pushes the item to the bottom (I want it on the right).
align-self: flex-end
将项目推到底部(我想要它在右边)。
I would very much prefer a solution using flex-box because my items have variable heights and should always be centered vertically.
我非常喜欢使用 flex-box 的解决方案,因为我的项目具有可变的高度,并且应该始终垂直居中。
What is the cleanest way to achieve this?
实现这一目标的最干净的方法是什么?
Thanks for your help!
谢谢你的帮助!
回答by ndm
Simple fix, use an auto-adjusting margin:
简单修复,使用自动调整边距:
ul li:last-child {
margin-left: auto;
}
You may also want to not use width: 100%
so that the element stays inside the visible area:
您可能还不想使用,width: 100%
以便元素保持在可见区域内:
ul {
display: flex;
justify-content: flex-start;
flex-direction: row;
align-items: center;
/* width: 100%; */
height: 100px;
background: #333;
padding: 15px;
}