浮动元素正确,但使其出现在HTML之后

时间:2016-03-01 23:30:54

标签: html css css-float

我有以下标记:

<style>
  button {
    float: right;
  }

  @media only screen and (max-width: 480px) {
    button {
      width: 100%;
      float: none;
    }
  }
</style>

<div>
  <button>Book now</button>
  <p>Lorem ipsum...</p>
</div>

我想要的是:

  1. 让文字将媒体上的按钮包裹起来大型设备:
    text wrapping around button

  2. 在移动设备上的文字后有一个全宽按钮
    button full width after the text

  3. 但是,我无法同时获得这两者。

    如果我将按钮放在HTML中的文本之前,我会将文本包装好,但按钮会出现之前移动文本:

    button appears before text

    小提琴:https://jsfiddle.net/nswptc3s/1/

    如果我把按钮放在HTML后面的文本后面,那么按钮就会出现在手机上的文字之后,但文字并没有将按钮包裹在更大的设备上:

    text does not wrap button

    小提琴:https://jsfiddle.net/nswptc3s/2/

    如何同时获取两者?请注意,我不想为按钮或段落赋予固定的宽度(因此我不能只是浮动<p> )。

1 个答案:

答案 0 :(得分:1)

Floats不应该用于布局。更好地使用flexbox。

div {
  display: flex; /* Magic begins */
  align-items: center; /* Center button vertically */
}
p {
  flex: 1; /* Occupy the remaining space left by the button */
}
@media only screen and (max-width: 480px) {
  div {
    flex-direction: column; /* Switch to column layout */
    align-items: stretch; /* Stretch the button horizontally */
  }
}

&#13;
&#13;
div {
  display: flex;
  align-items: center;
}
p {
  flex: 1;
}
button {
  background: red;
  color: white;
  font-size: 16px;
  padding: 10px;
  border-radius: 5px;
  border: transparent;
}
@media only screen and (max-width: 480px) {
  div {
    flex-direction: column;
    align-items: stretch;
  }
}
&#13;
<div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum id eleifend velit. Maecenas feugiat consequat finibus. Aenean enim quam, tincidunt nec laoreet a, scelerisque et dolor.
  </p>
  <button>
    Book now
  </button>
</div>
&#13;
&#13;
&#13;