Bootstrap 4和SCSS-基于基类的替代主要

时间:2018-08-13 10:51:00

标签: css webpack sass bootstrap-4

我正在将Bootstrap 4与Webpack一起构建在一个框架上的多站点应用程序。

我想根据body元素上的基类动态更改Bootstrap的某些变量。即:

.class1{
    $theme-colours: (
        primary: red,
    );
 }

.class2{
    $theme-colours: (
        primary: blue,
    );
 }

然后:

<body class="class1">
    <h1 class="text-primary">RED TEXT</h1> 
</body>

并且:

<body class="class2">
    <h1 class="text-primary">BLUE TEXT</h1> 
</body>

在SASS中有可能吗?我尝试使用mixin,但没有成功...

1 个答案:

答案 0 :(得分:0)

您必须使用各种Bootstrap 4主题颜色功能/混合器“重建” -primary类。可以将主要颜色更改放入自定义@mixin中,从而更容易构建每个主要“主题”:

@mixin build-primary-classes($color) {
    @include bg-variant(".bg-primary", $color);

    .btn-primary {
        @include button-variant($color, $color);
    }

    .btn-outline-primary {
        @include button-outline-variant($color);
    }

    @include text-emphasis-variant(".text-primary", $color);

    .border-primary {
        border-color: $color !important;
    }
}


.theme1 {
    @include build-primary-classes($purple);
}

.theme2 {
    @include build-primary-classes($red);
}

https://www.codeply.com/go/c3KTMWlDCb

再进一步,您可以将“ $ customthemes”放置在地图中,然后生成主题类。

$customthemes: (
  "theme1": purple,
  "theme2": cyan,
  "theme3": orange
);

@each $themeName, $color in $customthemes {
  .#{$themeName} {
    @include build-primary-classes($color);
  }
}

https://www.codeply.com/go/81ukKyAZbS


然后,如果您使用的是Webpack,请将$customthemes映射传递到extract-text-webpack-plugin和SASS-loader。使用data选项传递$ customthemes ...

webpack-config:

     ....
     use: extractSass.extract({
         use: [

                  {
                    loader: "sass-loader",
                    options: {
                      allChunks: true,
                      data: '$customthemes:("theme1":purple,"theme2":pink,"theme3":red);'
                    }
                }]
         })
      .....

请记住,如果$ customthemes过多,则CSS会变得很大。我更喜欢使用SASS生成单独的theme.css文件,然后根据需要在HTML HEAD中引用任何theme.css

相关:
How to extend/modify (customize) Bootstrap 4 with SASS
How to change the bootstrap primary color?