Lan Mai
Lan Mai

Reputation: 375

Flexbox wrap items on demand?

I currently have a model like this

 .parent
   .child1
   .child2
   .child3
   .child4

The request is: 'parent' is a row that takes full width of the device.

In big screen, there is one row with 4 children.

In smaller screen, there are 2 rows with 2 columns each.

And in the extra small screen there are 1 column with 4 rows.

Is there any way that I can achieve the request using only Flexbox? (because I hate Boostrap so much...)

I tried flex-wrap: wrap for the parent and flex: 1 for the children, but failed :(

Thank you :)

Upvotes: 1

Views: 182

Answers (2)

Michael Benjamin
Michael Benjamin

Reputation: 370973

.container {
    display: flex;
}

.box {
    flex: 1;
}

@media ( max-width: 800px ) {
  .container { flex-wrap: wrap; }
  .box { flex: 0 0 50%; box-sizing: border-box; }
}

@media ( max-width: 500px ) {
  .box { flex-basis: 100%; }
}

/* non-essential decorative styles */
.box {
    height: 50px;
    background-color: lightgreen;
    border: 1px solid #ccc;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 1.2em;
}
<div class="container">
    <div class="box"><span>1</span></div>
    <div class="box"><span>2</span></div>
    <div class="box"><span>3</span></div>
    <div class="box"><span>4</span></div>
</div>

jsFiddle

Upvotes: 1

vsync
vsync

Reputation: 130055

This is a SCSS mixin that does that:

@mixin n-columns($min-width, $gutter, $last-equal:false, $max-cols:5, $selector:'.colItem'){
    display: flex;
    flex-wrap: wrap;
    margin-left: -$gutter;
    // margin-top: -$gutter;
    position: relative;
    top: -$gutter;

    > #{$selector} {
        flex: 1 0 auto;
        margin-left: $gutter;
        margin-top: $gutter;

        @if $last-equal {
            @for $i from 2 through $max-cols {
                $screen-width: ($min-width*$i)+($gutter*$i);
                $column-width: (100%/$i);
                @media( min-width: $screen-width) {
                        max-width: calc(#{$column-width} - #{$gutter});
                }
            }

            $column-width: (100%/$max-cols);
            @media( min-width: $min-width*$max-cols) {
                    min-width: calc(#{$column-width} - #{$gutter});
            }
        }
    }
}

You use it like so:

.parent{
    @include n-columns(200px, 3px, true, 5);
}

You'll understand all the things it can do after you use it with different settings and see the results, it's pretty straightforward.

Upvotes: 2

Related Questions