【发布时间】:2018-12-06 21:31:57
【问题描述】:
我需要将两个元素放在父元素的右侧,但是,当使用float: right 属性时,它会使元素切换位置。
我看过这个帖子:Prevent Right Floated Elements from Swapping 但是,添加display: inline-block 和text-align: right 并没有解决问题。
这是一个
.container {
width: 300px;
height: 20px;
background-color: red;
margin: 0 auto;
}
.element1 {
float: right;
height: 20px;
width: 10px;
background-color: blue;
color: white;
padding: 10px;
}
.element2 {
float: right;
height: 20px;
width: 10px;
background-color: yellow;
padding: 10px;
}
<div class="container">
<div class="element1">1</div>
<div class="element2">2</div>
</div>
我想要的结果是蓝色元素后跟黄色元素。
更新:
我确实理解这是预期的行为,第二个元素在第一个元素之后一直发送到右侧,我知道更改元素可以解决问题,但是,只是想知道是否存在CSS 解决方案。
【问题讨论】:
-
你应该使用
display: flex -
您链接到的问题的答案建议在 .container 上使用
display: inline-block;和text-align: right;,这样就不需要在元素上使用float: right。正如@HerrSerker 建议的那样,您也可以尝试一下 flexbox(在这种情况下,您需要在容器上使用align-items: flex-end) -
在我的容器中,我还有其他一些向左浮动的项目,弹性框会考虑到这一点吗?
-
您也应该在您的问题中提到这一点。是的:见这里codepen.io/HerrSerker/pen/dQxMdO