我有以下标记:
<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>
我想要的是:
但是,我无法同时获得两者。
如果我在 HTML 中将按钮放在文本之前,我可以让文本自动换行,但在移动设备上按钮出现在文本之前:
fiddle :https://jsfiddle.net/nswptc3s/1/
如果我在 HTML 中将按钮放在文本之后,按钮会在移动设备上显示在文本之后,但文本不会在较大的设备上包裹按钮:
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/