当用户缩小浏览器窗口时,如何使2个或多个水平div堆叠为垂直div? [英] How do I make 2 or more horizontal divs stack into a vertical div when the user shrinks the browser window?
问题描述
我在同一行上有2个div,每个div的宽度为50%,左侧为浮点数.如果用户正在通过智能手机查看页面,我希望它们可以堆叠在一起.现在,即使浏览器窗口缩小到300px或从智能手机查看,div仍保持在同一行.
I have 2 divs on same row, each with a width of 50% and a float: left. I would like them to stack one on top of the other if the user is viewing the page from a smart-phone. Right now, the divs remain on the same row even if the browser window is narrowed to 300px or if viewed from a smart-phone.
推荐答案
媒体查询是解决之道.我将采用移动优先的方法,并添加媒体查询以扩大设计范围.即,以divs not 浮动开始,并在屏幕尺寸达到一定大小时添加浮动和宽度:
Media queries is the way to go. I'd go with a mobile-first approach, and add media queries to scale up the design. I.e, start with the divs not floating, and add float and width when the screen estate reaches a certain size:
<!-- HTML -->
<div class="wrapper">
<div class="column">
<p>This is column 1</p>
</div>
<div class="column">
<p>This is column 2</p>
</div>
</div>
/* CSS */
.wrapper {
/* Ensure wrapper contains the columns, even when they are floated, by
creating a new Block formatting context */
overflow: hidden;
}
.column {
/* Ensure we have some margins when the columns are collapsed, or
other content is displayed below. */
margin-bottom: 2em;
}
/* Edit the min-width condition to match your desired breakpoint. */
@media screen and (min-width: 400px) {
.wrapper .column {
width: 50%;
float: left;
}
}
此处的实时演示: http://jsfiddle.net/jPgWL/
这篇关于当用户缩小浏览器窗口时,如何使2个或多个水平div堆叠为垂直div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!