如何在 scss 类中导入 scss 文件

Kum*_* Sd 6 css sass angular

当我向正文添加“深色主题”类时,我想添加不同的主题。我的实现如下所示:

@import '../../../../node_modules/angular-grids/styles/material.scss';

.app-dark {
  @import '../../../../node_modules/angular-grids/styles/material-dark.scss';
}
Run Code Online (Sandbox Code Playgroud)

没有任何运气。关于如何执行此操作有任何线索吗?

Tha*_*guy 4

有两种方法可以做到这一点。它们都包含 mixin。

元加载CSS

sass:meta功能使您能够做您想做的事情。

假设您有一个带有主题的 scss 文件:

//theme/_code.scss
$border-contrast: false !default;

code {
  background-color: #6b717f;
  color: #d2e1dd;
  @if $border-contrast {
    border-color: #dadbdf;
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以将该代码包含在另一个 scss 文件中,如下所示:

// other-theme.scss
@use "sass:meta";

body.dark {
  @include meta.load-css("theme/code",
      $with: ("border-contrast": true));
}
Run Code Online (Sandbox Code Playgroud)

这将产生以下 css:

body.dark code {
  background-color: #6b717f;
  color: #d2e1dd;
  border-color: #dadbdf;
}

Run Code Online (Sandbox Code Playgroud)

您可以在此处阅读有关此功能的更多信息

老式的混合

但是如果您使用mixin 和 include ,您基本上可以做同样的事情。

因此,假设您想将此类导入到另一个类中:

.title {
  font-size: 2em;
  font-weight: bold;
}

Run Code Online (Sandbox Code Playgroud)

另一个带有另一个主题的 sass 文件:

.dark-theme {
  .title {
    font-size: 2em;
    font-weight: bold;
    color: white;
  }
}

Run Code Online (Sandbox Code Playgroud)

您可以使用 scss mixin 并将其导入到两个文件中:

mixin.scss

@mixin shared-items() {
  .title {
    font-size: 2em;
    font-weight: bold;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,在主题文件中:

白色主题.scss

@import './mixin.scss';

/* will be included as is without a parent class */
@include shared-items;
Run Code Online (Sandbox Code Playgroud)

黑暗主题.scss

@import './mixin.scss';

/* will be included inside the dark-theme class */
.dark-theme {
  .title {
    color: white;
  }

  @include shared-items;
}
Run Code Online (Sandbox Code Playgroud)

这将生成这个CSS:

.title {
  font-size: 2em;
  font-weight: bold;
}

.dark-theme {
  .title { color: white; }
  .title {
    font-size: 2em;
    font-weight: bold;
  }
}

Run Code Online (Sandbox Code Playgroud)

请注意,您还可以将参数传递给 mixin 并将它们用作函数。因此,您可以轻松传递颜色并将它们与主题变量一起使用。

例如:

/* an example of giving a color to a placeholder mixin: */
@mixin nk-placeholder($color: #C4C4CC) {
    &::-webkit-input-placeholder {
        color: $color;
        font: inherit;
    }
    &::-moz-placeholder {
        color: $color;
        font: inherit;
    }
    &:-ms-input-placeholder {
        color: $color;
        font: inherit;
    }
    &:-moz-placeholder {
        color: $color;
        font: inherit;
    }
    &::placeholder {
        color: $color;
        font: inherit;
    }
}

/* same thing as above */
@mixin shared-items($text-color: black) {
  .title {
    font-size: 2em;
    font-weight: bold;
    color: $text-color;
  }
}


.white-theme {
  @include shared-items;
}

.dark-theme {
  @include shared-items(white);
}
Run Code Online (Sandbox Code Playgroud)