How do I make 2 or more horizontal divs stack into a vertical div when the user shrinks the browser window?

痞子三分冷 提交于 2019-12-20 04:24:05

问题


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.


回答1:


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

Live demo here: http://jsfiddle.net/jPgWL/




回答2:


Use media queries:

@media screen and (min-width: 321px) {
  #wrapper {width: 100%;}
  .content {
    width: 50%;
    float: left;
  }
}
@media screen and (max-width: 320px) {
  #wrapper {width: 100%;}
  .content {
    width: 100%;
    float: none;
  }
}


来源:https://stackoverflow.com/questions/15265530/how-do-i-make-2-or-more-horizontal-divs-stack-into-a-vertical-div-when-the-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!