我创建了一个基本的mixin来计算宽度并为我的rems提供像素回退。这工作正常,但我现在想使用这些列宽用于说负边距。我已经尝试了几个使用@if和插值来实现正确输出的想法,但是我想对逻辑提出一些建议。也有人可以解释为什么错误的输出增加了。
$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;}
提前干杯。
答案 0 :(得分:0)
round($cols * ($column-width + $gutter-width) - $gutter-width);
有了负号,所有这一切都转向了补充
答案 1 :(得分:0)
您需要的功能是abs()
。这将允许您在进行计算之前去除负号,然后在最后重新添加:
@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);
}
输出:
.div {
margin-left: 280px;
margin-left: -280px;
}