How to control number of items per row using media queries in Flexbox?

后端 未结 2 885
广开言路
广开言路 2020-12-01 06:25

So imagine I have the following Markup

2条回答
  •  一整个雨季
    2020-12-01 06:55

    I had to get rid of the margin around the blocks, because percentage widths are difficult to cleanly apply to elements with margins, but you can see the changes at http://codepen.io/anon/pen/jPeLYb?editors=110 :

    @mixin max-width($width) {
        @media screen and (max-width: $width) {
            @content;
        }
    }
    
    .container {
        position: relative;
        display: flex;
        flex-flow: row wrap;
    }
    .item {
        background-color: tomato;
        box-sizing: border-box;
        padding: 20px;
        outline: 2px solid blue;
        flex: 1;
    }
    
    @include max-width(992px) {
        .item {
            flex-basis: 25%;
            background-color: red;
        }
    }
    
    @include max-width(640px) {
        .item {
            flex-basis: 50%;
            background-color: green;
        }
    }
    

    The important parts here are:

    • flex-flow: row wrap which allows the flexbox to appear on multiple rows (the default is nowrap)

    • flex-basis which is the equivalent of width in this case

    • position: relative which makes the widths relative to the container, rather than the body (this would screw up the rounding)

提交回复
热议问题