Question

I have created a basic mixin to calculate widths and provide a pixel fallback for my rems. This is working ok, but I would now like to use these column widths for use say in a negative margin. I have tried several ideas using @if and interpolation to achieve the correct output but would like some advice on the logic please. Also could someone explain why the incorrect output has increased.

$column-width:    40;       // set column width
$gutter-width:    20;       // set gutter width

$font-size: 16;
$rem: $font-size / 1rem;    // convert px to rem

// Mixin for pixel fallback
@mixin rem($property, $pixel) {
    #{$property}: $pixel * 1px;
    #{$property}: $pixel / $rem;
}
// function to calculate column widths
@function calculate-width($cols) {
    $width: round($cols * ($column-width + $gutter-width) - $gutter-width);
    @return $width;
}

// Mixin to select property and widths
@mixin width($property, $cols) {
    @include rem($property, calculate-width($cols));
}

// Usage that works
.div{ @include width(margin-right, 5); }

// Output that is correct
.div{
margin-right: 280px;
margin-right: 17.5rem;}

// Usage that is incorrect (note the minus sign before 5)
.div{ @include width(margin-right, -5); }

//Output that is incorrent
.div{
margin-right: -320px;
margin-right: -20rem;}

Cheers, in advance.

Était-ce utile?

La solution

The function you're needing is abs(). This will allow you to strip out the negative sign before you do your calculation, then add it back on at the end:

@function calculate-width($cols) {
  $width: round(abs($cols) * ($column-width + $gutter-width) - $gutter-width);
  @return $width * ($cols / abs($cols));
}

.div {
  @include width(margin-left, 5);
  @include width(margin-left, -5);
}

Output:

.div {
  margin-left: 280px;
  margin-left: -280px;
}

Autres conseils

round($cols * ($column-width + $gutter-width) - $gutter-width);

With the negative sign all this thing turned to addition

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top