0

I'm trying to create a column-based layout with specific gutter sizes using flexbox.

I would like to include the option to add a class like col-2 to a given element that would make that element the size of 2 of the other elements in that row, for instance. col-3 for the size of 3 elements, col-4 for 4, etc.

I am doing this by altering the flex property of the element to which the col-n class is added.

SCSS mixins

// number of columns
$columns: 8;

// column proportions mixin
@mixin column-prop($n) {
    flex: $columns * $n;
}

.col-2 {
    @include column-prop(2);
}
.col-3 {
    @include column-prop(3);
}
.col-4 {
    @include column-prop(4);
}
...

HTML

<div class="grid">
    <div>flex: 8</div>
    <div>flex: 8</div>
    <div class="col-2">flex: 16</div>
</div>

<div class="grid">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
</div>

<div class="grid">
    <div>flex: 8</div>
    <div>flex: 8</div>
    <div>flex: 8</div>
    <div>flex: 8</div>
    <div class="col-4">flex: 32</div>
</div>

This works if I do not use any padding: enter image description here But if I add padding, the padding is sized in addition, to the content (as if its a content-box) despite my having set box-sizing: border-box;on all child elements. enter image description here I believe box-sizing: border-box; does not work for flex items.

How can I simply have the padding be included in the size of each element as if they are boxer-box elements?

yevg
  • 1,846
  • 9
  • 34
  • 70
  • It looks like the problem might be the `flex-shrink` component of the `flex` property you're using. https://stackoverflow.com/q/34753491/3597276 – Michael Benjamin Dec 05 '19 at 03:35

1 Answers1

-3

Edit: CSS-grid includes support for gutters. Let me take a crack at it...

HTML

<div class="grid-32">
  <div>flex: 8</div>
  <div>flex: 8</div>
  <div class="col-2">flex: 16</div>
</div>

<div class="grid-32">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

<div class="grid-64">
  <div>flex: 8</div>
  <div>flex: 8</div>
  <div>flex: 8</div>
  <div>flex: 8</div>
  <div class="col-4">flex: 32</div>
</div>

SASS

// number of columns
$columns: 8;

@mixin make-grid($n) {
  .grid-#{$n} {
    display: grid;
    width: 100%;
    grid-template-columns: repeat($n, 1fr);
    grid-column-gap: 1em;
    margin-bottom: 1em;
    div {
      grid-column-end: span $columns;
      background: #ccc;
      @for $i from 1 through 4 {
        &.col-#{$i} {
          grid-column-end: span $i*$columns;
          background: hsl($i * 256/$columns, 50%, 50%);
        }
      }
    }
  }
}

@include make-grid(4*$columns);
@include make-grid(8*$columns);

What I learned is that, though css-grid handles the gutters perfectly, you do need to know the total columns ahead of time. If you do know, this is a good way to get what you need.

Codepen: https://codepen.io/bstees/pen/rNaVJvR

Brent Stees
  • 342
  • 1
  • 5