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

后端 未结 2 1186
时光取名叫无心
时光取名叫无心 2021-01-24 19:38

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. Rig

2条回答
  •  清歌不尽
    2021-01-24 20:17

    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:

    
    

    This is column 1

    This is column 2


    /* 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/

提交回复
热议问题