只有当第二个div适合第一个div时才向右浮动

时间:2016-02-21 11:27:09

标签: 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的浮点数,例如;

Some text for div 1
Some text for div 2

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:3)

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>

答案 1 :(得分:1)

我没有flexbox和更多跨浏览器的变种

&#13;
&#13;
.container{
  font-size: 0;
  text-align: justify;
}
.container::after{
  content: "";
  display: inline-block;
  width: 100%;
  height: 0;
  visibility: hidden;
}
.class-1, .class-2{
  display: inline-block;
  font-size: 14px;
  text-align: left;
}
&#13;
<div class="container">
  <div class="class-1">Some text for div 1</div>
  <div class="class-2">Some text for div 2</div>
</div>
&#13;
&#13;
&#13;