【问题标题】:When float two elements right they switch positions当两个元素向右浮动时,它们会切换位置
【发布时间】:2018-12-06 21:31:57
【问题描述】:

我需要将两个元素放在父元素的右侧,但是,当使用float: right 属性时,它会使元素切换位置。

我看过这个帖子:Prevent Right Floated Elements from Swapping 但是,添加display: inline-blocktext-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

标签: html css css-float


【解决方案1】:

.container {
  display: flex;
}

.element4 {
  margin-right: auto;
}
.element5 {
  margin-left: auto;
}

.container {
  width: 300px;
  background-color: red;
}

.element {
  height: 20px;
  width: 10px;
  padding: 10px;
}


.element1 {
  background-color: blue;
  color: white;
}
.element2 {
  background-color: yellow;
  color: black;
}

.element3 {
  background-color: green;
  color: white;
}
.element4 {
  background-color: gold;
  color: black;
}

.element5 {
  background-color: magenta;
  color: black;
}
.element6 {
  background-color: goldenrod;
  color: white;
}
<div class="container">
  <div class="element element1">1</div>
  <div class="element element2">2</div>
  <div class="element element3">3</div>
  <div class="element element4">4</div>
  <div class="element element5">5</div>
  <div class="element element6">6</div>
</div>

【讨论】:

【解决方案2】:

这是预期的行为,要么在 HTML 中切换元素,要么使用浮动以外的其他定位方法。

它首先浮动第一个元素,然后它看到下一个元素,然后需要再次浮动它,以便它超过原来的元素。

【讨论】:

  • 是的,我知道这是预期的行为,第二个元素在第一个元素之后一直发送到右侧。我只是想知道是否有针对该问题的 CSS 解决方案而不是更改 HTML。
【解决方案3】:

使用这个。

.container{
  width: 300px;
  height: 20px;
  background-color: red;
  margin: 0 auto;
  position:relative;
}
.element1 {
  position:absolute;
  right:0;
  height: 20px;
  width: 10px;
  background-color: blue;
}
.element2 {
  position:absolute;
  right:10px;
  height: 20px;
  width: 10px;
  background-color: yellow;
}
<div class="container">
  <div class="element1">
  </div>
  <div class="element2">
  </div>
</div>

【讨论】:

  • 结果还是一样。元素 2 |元素 1. 我需要什么 元素 1 |元素 2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-25
  • 2017-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-16
  • 1970-01-01
相关资源
最近更新 更多