Bas
Bas

Reputation: 2210

SASS calculate column widths for grid

I have written this piece of code to calculate column widths for my grid system:

@mixin calc-width($index, $type) {
  $column-calculation: (100% - ($gutter-width-procent * ($column-count - 1))) / $column-count;
  $column-width: ($column-calculation * $index);
  $gutter: ($gutter-width-procent * ($index - 1));
  @if ($index > 0) {
    @if ($type != 'width') {
      #{$type}: $column-width + $gutter + $gutter-width-procent;
    } @else {
      #{$type}: $column-width + $gutter;
    }
  }
}

I am calling that up in a different function like this:

  @for $index from 1 through $column-count {
    &.size-#{$index} {
      @include calc-width($index, 'width');
    }
  }

With the variables of:

$column-count: 12 !default; //12
$row-max-width: 1024;

$gutter-width-px: 15px !default; //In px
$gutter-width-procent: percentage($gutter-width-px / $row-max-width);

I like the system. But there is one thing that doesnt seem correct...

Can i do this line on another way, then substracting from 100%?

$column-calculation: (100% - ($gutter-width-procent * ($column-count - 1))) / $column-count;

Upvotes: 0

Views: 2245

Answers (2)

mrksbnch
mrksbnch

Reputation: 1842

Not really sure, if this solves your problem, but i wouldn't create the grid gutters like that. You can easily create them if you use "box-sizing", a negative margin on the parent and a padding for every column. So your ("pseudo")-HTML could look like:

.parent
    .column
    .column
    .column

And your CSS like that:

.parent {
    margin-left: -GUTTER;
}
.child {
    padding-left: GUTTER;
}

Your SASS function to create the widths for the columns could then be simplified as well. I made a pen to show you one way to solve your gutter problem.

This SASS function is just for testing and doesn't check for duplicates (.size1-2 (50%) and .size2-4) and other stuff.

Upvotes: 0

user319940
user319940

Reputation: 3317

I may be getting the wrong end of the stick here but if if you used box-sizing: border-box; and padding for your gutters then you wouldn't have to do any calculation. There's a great post about border-box here.

Upvotes: 1

Related Questions