css - 仅当第二个 div 适合第一个时,才将其 float 到右侧

标签 css css-float

我有以下(简化的)html 和 css:

<div class="container">
  <div class="one">Some text for div 1</div>
  <div class="two">Some text for div 2</div>
</div>

<style>
  .two {float: right}
</style>

当两个元素都放在容器中时,我希望它看起来像;

Some text for div 1                                                     Some text for div 2

但是,当它们不适合彼此相邻时,我希望删除第二个 div 的 float ,例如;

Some text for div 1
Some text for div 2

我怎样才能做到这一点?

最佳答案

Flexbox 可以做到这一点;

.parent {
  border: 1px solid red;
  margin: 1em auto;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.skinny {
  width: 60%;
}
.left {
  height: 50px;
  background: green;
  flex: 0 0 250px
}
.right {
  height: 50px;
  background: pink;
  flex: 0 0 250px;
}
<div class="parent">
  <div class="left"></div>
  <div class="right"></div>
</div>

<div class="parent skinny">
  <div class="left"></div>
  <div class="right"></div>
</div>

关于css - 仅当第二个 div 适合第一个时,才将其 float 到右侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35535514/

相关文章:

CSS选择样式为="float:left"的图像可能吗?

html 元素未使用 colspan 排列

asp.net - 水平并排设置两个 <divs>

css - 无法在 CSS 中显示边距

css - IMG 没有显示上面的背景颜色?

html - 标题标签内的多个 div

PHP 内容未显示

javascript - 移动文本框动画

html - CSS flex : Text escapes from container

css - Chrome 加载强制 float :right to new line