弹性框按需包装项目



我目前有这样的模型

 .parent
   .child1
   .child2
   .child3
   .child4

请求是:"父"是占用设备全宽的行。

在大屏幕上,有一排4个孩子。

在较小的屏幕中,有 2 行,每行 2 列。

在超小屏幕中,有 1 列 4 行。

有什么方法可以仅使用弹性框来实现请求吗?(因为我太讨厌Boostrap了...

我尝试为父母flex-wrap: wrap,为孩子flex: 1,但失败:(

谢谢:)

这是一个SCSS的混合,可以做到这一点:

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

你像这样使用它:

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

在使用它与不同的设置一起使用并查看结果后,您将了解它可以执行的所有操作,这非常简单。

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

js小提琴

最新更新