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

标签 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. 在移动设备上的文本之后有一个全 Angular 按钮:
    button full width after the text

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


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

button appears before text

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


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

text does not wrap button

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


我怎样才能同时获得这两者?请注意,我不想为按钮或段落提供固定宽度(因此我也不能只 float <p>)。

最佳答案

float 不应该用于布局。最好使用 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>

关于html - 向右浮动元素,但使其出现在 HTML 之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35735714/

相关文章:

javascript - BsMultiSelect 和 jQuery 验证兼容性

javascript - 动态视频上的毛玻璃效果

javascript - 完全由javascript生成的网站布局是错误的吗?

html - 并排 float 的元素,当空间不足时,这些元素会落到它们自己的行中

html - 在另一个 div 中时让一个 div 向左浮动

JavaScript 与选项交互

html - 如何控制<abbr>元素

html - 在不移动文本的情况下,底部边框延伸到 div 末尾的表单输入

html - 两列布局,其中主要内容 DIV 的宽度是可变的(使用所有可用空间 100%)

css - 两列 float (右和左)但内容在中间