【问题标题】:Use of margin and padding variables in Sass in custom class Bootstap 4在自定义类 Bootstrap 4 中使用 Sass 中的边距和填充变量
【发布时间】:2020-04-19 03:45:13
【问题描述】:

我想知道如何在自定义类中使用 Bootsrap 来通用化间隔变量。

我有一个类 .box 并想应用 bootstrap 4 的类 pl-3。 我不想在 HTML 中添加内联类,但想在 sass 中设置样式。

我想使用 Bootstap 的间隔变量,而不是在类本身中硬编码。因此,如果我以后想更改填充,我只需要更改 sass 中的填充即可。

我定义了以下内容:

$spacer: 1rem !default;    
$spacers: (
      0: 0,
      1: ($spacer * .125),      // 2px
      2: ($spacer * .25),       // 4px
      3: ($spacer * .375),      // 6px
      4: ($spacer * .5),        // 8px
      5: ($spacer * 0.75),      // 12px
      6: ($spacer * 1)          // 16px
    )

最好的方法是什么? 我发现是这样的:

.box{
   @extend .pl-3;
}

但我不喜欢这样。这不是很自我解释 有没有其他/更好的方法来做到这一点?喜欢:

.box{
       padding-left: $spacer-3;
    }

【问题讨论】:

  • 第一件事是用具有相同变量名的自定义值覆盖默认值的糟糕方法其次,如果我没有错,您只需在 sass 中初始化可行的值,如 $custom-space-5: 5px,然后在 @ 987654325@ 你可以像.box{padding:$custom-space-5} 一样使用它,所以当你改变变量的值时,它会改变它使用的地方。

标签: html css sass bootstrap-4 padding


【解决方案1】:

将 SCSS 函数 map-get() 用作 documented here

.box {
  padding-left: map-get($spacers, 3);
}

Codepen

【讨论】:

    【解决方案2】:

    你可以使用一个简单的函数(注意 Sass 列表从索引 1 开始,为什么我们使用 $n +1)

    @function space($n){ 
      @return nth(0 .125 .25 .375 .5 .75 1, $n + 1) * 1rem;
    }
    
    
    .box{
       padding-left: space(3);  // 0.375rem;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-02
      • 2016-12-19
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-11
      • 1970-01-01
      相关资源
      最近更新 更多