向右浮动元素,但使其出现在 HTML 之后

Float element right, but make it appear after in the HTML

我有以下标记:

<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. 让文本在大中型设备上环绕按钮:

  2. 在移动设备上文本之后有一个全角按钮:

然而,我无法同时获得两者。


如果我将按钮放在 HTML 中的文本之前,我可以让文本自动换行,但按钮出现在 之前 手机上的文本:

Fiddle: https://jsfiddle.net/nswptc3s/1/


如果我在 HTML 中将按钮放在文本之后,按钮会在移动设备上显示在文本之后,但在较大的设备上文本不会环绕按钮:

Fiddle: https://jsfiddle.net/nswptc3s/2/


我怎样才能同时获得两者?请注意,我不想为按钮或段落提供固定宽度(所以我不能只浮动 <p>

浮动不应该用于布局。最好使用 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 */
  }
}

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;
  }
}
<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>