如何避免 SCSS 中的样式重复? [英] How to avoid duplication of styles in SCSS?

查看:66
本文介绍了如何避免 SCSS 中的样式重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个 .scss 文件,其中包含所有其余 .scss 文件的一些变量.但是如果我这样做,它的 .scss 样式会在我所有的 .scss 文件中重复:

I want to have one .scss file with some varibles for all the rest .scss files. But if I do so its .scss styles are duplicated in all my .scss files:

global.scss - 我的全局变量和样式文件

global.scss - my global variables and styles file

$white: #FFF;
$black: #000;
$bg_red: red;

.mt30 {
    margin-top: 30px;
}

header.scss - 我想在这个文件中使用全局变量和样式.

header.scss - I want to use global vars and styles in this file.

@include "global"

.foo {
    width: 100px;
    height: 50px;
    backgrounnd-color: $bg_red;
}

ma​​in.scss - 我也想在这个文件中使用全局变量和样式.

main.scss - I want to use global vars and styles in this file too.

@include "global"

.boo {
    width: 100px;
    height: 50px;
    backgrounnd-color: $white;
}

但是每个最终的 .css 文件都有来自 global.scss 的样式.所以我的页面上有几个 .mt30 样式.如何避免?

But each final .css file has styles from global.scss. So I have several .mt30 styles on my page. How to avoid it?

推荐答案

问题似乎不是样式重复,而是库或配置文件的重复.为此,所需要的只是稍微不同地构建您的代码.首先将 global.scss 文件的名称(以及所有其他部分)更改为以下划线开头的部分文件,_global.scss.然后,创建一个清单文件,如 app.scss.在里面,导入 _global.scss 和你需要的任何其他文件.这些其他文件现在可以访问 app.scss 可以访问的所有内容:

It seems that the issue isn't the duplication of styles, but the duplication of libraries, or configuration files. For that, all it takes is to just structure your code a little differently. Start by making your global.scss file a partial by changing its name (as well as all the other pieces) to start with an underscore, _global.scss. Then, create a manifest file, like app.scss. Inside there, import _global.scss and whatever other files you need. Those other files will now have access to everything that app.scss has access to:

_global.scss

$white: #FFF;
$black: #000;
$bg_red: red;

_header.scss

.foo {
  width: 100px;
  height: 50px;
  background-color: $bg_red;
}

_main.scss

.mt30 {
  margin-top: 30px;
}

.boo {
  width: 100px;
  height: 50px;
  background-color: $white;
}

app.scss

// Import libraries and config; adding compass as an example
@import "global";
@import "compass/css3";

// Actual selectors
@import "header";
@import "main";

因为您在 header 和 main 之前导入 global,所以后两者将可以访问前者中的任何内容.还要注意的是,我将一个声明的样式 .mt30 从全局移到主要部分,只是为了确保没有在全局配置文件中声明任何样式.

Because you're importing global before header and main, the latter two will have access to whatever's in the former. Also to note is that I moved the one declared style, .mt30, out from global into the main partial, only to make sure no styles were being declared in the global config file.

这篇关于如何避免 SCSS 中的样式重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆