我有以下标记:
<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中的文本之前,我会将文本包装好,但按钮会出现之前移动文本:
小提琴:https://jsfiddle.net/nswptc3s/1/
如果我把按钮放在HTML后面的文本后面,那么按钮就会出现在手机上的文字之后,但文字并没有将按钮包裹在更大的设备上:
小提琴:https://jsfiddle.net/nswptc3s/2/
如何同时获取两者?请注意,我不想为按钮或段落赋予固定的宽度(因此我不能只是浮动<p>
)。
答案 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 */
}
}
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;