Flex-box: Align last row to grid

后端 未结 29 2535
不知归路
不知归路 2020-11-22 02:54

I have a simple flex-box layout with a container like:

.grid {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

29条回答
  •  梦谈多话
    2020-11-22 03:08

    Here's another couple of scss mixins.

    These mixins assume that you are not going to use js plugins like Isotope (they don't respect html markup order, thus messing up with css nth rules).

    Also, you will be able to take full advantage of them especially if you're writing your responsive breakpoints in a mobile first manner. You ideally will use flexbox_grid() on the smaller breakpoint and flexbox_cell() on the following breakpoints. flexbox_cell() will take care of resetting previously setted margins no longer used on larger breakpoints.

    And by the way, as long as you correctly setup your container's flex properties, you can also use only flexbox_cell() on the items, if you need to.

    Here's the code:

    // apply to the container (for ex. 
      element) @mixin flexbox_grid($columns, $gutter_width){ display: flex; flex-direction:row; flex-wrap:wrap; justify-content: flex-start; > *{ @include flexbox_cell($columns, $gutter_width); } } // apply to the cell (for ex. a
    • element) @mixin flexbox_cell($columns, $gutter_width){ $base_width: 100 / $columns; $gutters: $columns - 1; $gutter_offset: $gutter_width * $gutters / $columns; flex-grow: 0; flex-shrink: 1; flex-basis: auto; // IE10 doesn't support calc() here box-sizing:border-box; // so you can freely apply borders/paddings to items width: calc( #{$base_width}% - #{$gutter_offset} ); // remove useless margins (for cascading breakponts) &:nth-child(#{$columns}n){ margin-right: 0; } // apply margin @for $i from 0 through ($gutters){ @if($i != 0){ &:nth-child(#{$columns}n+#{$i}){ margin-right: $gutter_width; } } } }

    Usage:

    ul{
       // just this:
       @include flexbox_grid(3,20px);
    }
    
    // and maybe in following breakpoints, 
    // where the container is already setted up, 
    // just change only the cells:
    
    li{
       @include flexbox_cell(4,40px);
    }
    

    Obviously, it's up to you to eventually set container's padding/margin/width and cell's bottom margins and the like.

    Hope it helps!

提交回复
热议问题