Sass 基础知识

在使用 Sass 之前,你需要在项目中进行设置。如果你只想浏览这里,请继续,但我们建议你先安装 Sass。到这里 如果你想了解如何设置所有内容。

预处理预处理 permalink

¥Preprocessing

CSS 本身可能很有趣,但样式表变得越来越大、越来越复杂并且更难维护。这就是预处理器可以提供帮助的地方。Sass 具有 CSS 中尚不存在的功能,例如嵌套、混合、继承以及其他可帮助你编写健壮、可维护的 CSS 的实用功能。

¥CSS on its own can be fun, but stylesheets are getting larger, more complex, and harder to maintain. This is where a preprocessor can help. Sass has features that don’t exist in CSS yet like nesting, mixins, inheritance, and other nifty goodies that help you write robust, maintainable CSS.

一旦你开始修改 Sass,它就会获取你预处理的 Sass 文件并将其保存为可以在你的网站中使用的普通 CSS 文件。

¥Once you start tinkering with Sass, it will take your preprocessed Sass file and save it as a normal CSS file that you can use in your website.

实现这一点的最直接方法是在你的终端中。安装 Sass 后,你可以使用 sass 命令将 Sass 编译为 CSS。你需要告诉 Sass 从哪个文件构建以及将 CSS 输出到哪里。例如,从终端运行 sass input.scss output.css 将采用单个 Sass 文件 input.scss,并将该文件编译为 output.css

¥The most direct way to make this happen is in your terminal. Once Sass is installed, you can compile your Sass to CSS using the sass command. You’ll need to tell Sass which file to build from, and where to output CSS to. For example, running sass input.scss output.css from your terminal would take a single Sass file, input.scss, and compile that file to output.css.

你还可以使用 --watch 标志查看单个文件或目录。watch 标志告诉 Sass 监视源文件的更改,并在每次保存 Sass 时重新编译 CSS。如果你想监视(而不是手动构建)你的 input.scss 文件,你只需将监视标志添加到你的命令中,如下所示:

¥You can also watch individual files or directories with the --watch flag. The watch flag tells Sass to watch your source files for changes, and re-compile CSS each time you save your Sass. If you wanted to watch (instead of manually build) your input.scss file, you’d just add the watch flag to your command, like so:

sass --watch input.scss output.css

你可以使用文件夹路径作为输入和输出,并用冒号分隔它们来监视和输出到目录。在这个例子中:

¥You can watch and output to directories by using folder paths as your input and output, and separating them with a colon. In this example:

sass --watch app/sass:public/stylesheets

Sass 会监视 app/sass 文件夹中的所有文件是否发生更改,并将 CSS 编译到 public/stylesheets 文件夹。

¥Sass would watch all files in the app/sass folder for changes, and compile CSS to the public/stylesheets folder.

💡 Fun fact:

Sass 有两种语法!SCSS 语法 (.scss) 最常用。它是 CSS 的超集,这意味着所有有效的 CSS 也是有效的 SCSS。缩进语法 (.sass) 更不寻常:它使用缩进而不是大括号来嵌套语句,并使用换行符而不是分号来分隔它们。我们所有的示例都可以使用两种语法。

¥Sass has two syntaxes! The SCSS syntax (.scss) is used most commonly. It’s a superset of CSS, which means all valid CSS is also valid SCSS. The indented syntax (.sass) is more unusual: it uses indentation rather than curly braces to nest statements, and newlines instead of semicolons to separate them. All our examples are available in both syntaxes.


变量变量 permalink

¥Variables

将变量视为存储要在整个样式表中重用的信息的一种方式。你可以存储颜色、字体堆栈或你认为想要重用的任何 CSS 值等内容。Sass 使用 $ 符号使某些内容成为变量。这是一个例子:

¥Think of variables as a way to store information that you want to reuse throughout your stylesheet. You can store things like colors, font stacks, or any CSS value you think you’ll want to reuse. Sass uses the $ symbol to make something a variable. Here’s an example:

Playground

SCSS Syntax

$font-stack: Helvetica, sans-serif;
$primary-color: #333;

body {
  font: 100% $font-stack;
  color: $primary-color;
}
Playground

Sass Syntax

$font-stack: Helvetica, sans-serif
$primary-color: #333

body
  font: 100% $font-stack
  color: $primary-color

CSS Output

body {
  font: 100% Helvetica, sans-serif;
  color: #333;
}



当 Sass 被处理时,它会获取我们为 $font-stack$primary-color 定义的变量,并输出正常的 CSS,并将我们的变量值放置在 CSS 中。当使用品牌颜色并使它们在整个网站上保持一致时,这可能非常强大。

¥When the Sass is processed, it takes the variables we define for the $font-stack and $primary-color and outputs normal CSS with our variable values placed in the CSS. This can be extremely powerful when working with brand colors and keeping them consistent throughout the site.


嵌套嵌套 permalink

¥Nesting

在编写 HTML 时,你可能已经注意到它具有清晰的嵌套和视觉层次结构。另一方面,CSS 则不然。

¥When writing HTML you’ve probably noticed that it has a clear nested and visual hierarchy. CSS, on the other hand, doesn’t.

Sass 允许你以遵循 HTML 相同视觉层次结构的方式嵌套 CSS 选择器。请注意,过度嵌套的规则会导致 CSS 质量过高,从而难以维护,并且通常被认为是不好的做法。

¥Sass will let you nest your CSS selectors in a way that follows the same visual hierarchy of your HTML. Be aware that overly nested rules will result in over-qualified CSS that could prove hard to maintain and is generally considered bad practice.

考虑到这一点,以下是网站导航的一些典型样式的示例:

¥With that in mind, here’s an example of some typical styles for a site’s navigation:

Playground

SCSS Syntax

nav {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  li { display: inline-block; }

  a {
    display: block;
    padding: 6px 12px;
    text-decoration: none;
  }
}
Playground

Sass Syntax

nav
  ul
    margin: 0
    padding: 0
    list-style: none

  li
    display: inline-block

  a
    display: block
    padding: 6px 12px
    text-decoration: none


CSS Output

nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
nav li {
  display: inline-block;
}
nav a {
  display: block;
  padding: 6px 12px;
  text-decoration: none;
}


你会注意到 ullia 选择器嵌套在 nav 选择器内。这是组织 CSS 并使其更具可读性的好方法。

¥You’ll notice that the ul, li, and a selectors are nested inside the nav selector. This is a great way to organize your CSS and make it more readable.


局部局部 permalink

¥Partials

你可以创建包含 CSS 小片段的部分 Sass 文件,你可以将这些 CSS 片段包含在其他 Sass 文件中。这是模块化 CSS 并帮助使事情更易于维护的好方法。部分文件是一个以下划线开头命名的 Sass 文件。你可以将其命名为 _partial.scss 之类的名称。下划线让 Sass 知道该文件只是部分文件,不应将其生成为 CSS 文件。Sass 部分与 @use 规则一起使用。

¥You can create partial Sass files that contain little snippets of CSS that you can include in other Sass files. This is a great way to modularize your CSS and help keep things easier to maintain. A partial is a Sass file named with a leading underscore. You might name it something like _partial.scss. The underscore lets Sass know that the file is only a partial file and that it should not be generated into a CSS file. Sass partials are used with the @use rule.


模块模块 permalink

¥Modules

兼容性:
Dart Sass
since 1.23.0
LibSass
Ruby Sass

Only Dart Sass currently supports @use. Users of other implementations must use the @import rule instead.

你不必将所有 Sass 写入一个文件中。你可以使用 @use 规则将其拆分。此规则将另一个 Sass 文件作为模块加载,这意味着你可以使用基于文件名的命名空间来引用 Sass 文件中的变量 混入函数。使用文件还将在编译输出中包含它生成的 CSS

¥You don’t have to write all your Sass in a single file. You can split it up however you want with the @use rule. This rule loads another Sass file as a module, which means you can refer to its variables, mixins, and functions in your Sass file with a namespace based on the filename. Using a file will also include the CSS it generates in your compiled output!

SCSS Syntax

// _base.scss
$font-stack: Helvetica, sans-serif;
$primary-color: #333;

body {
  font: 100% $font-stack;
  color: $primary-color;
}
// styles.scss
@use 'base';

.inverse {
  background-color: base.$primary-color;
  color: white;
}

Sass Syntax

// _base.sass
$font-stack: Helvetica, sans-serif
$primary-color: #333

body
  font: 100% $font-stack
  color: $primary-color

// styles.sass
@use 'base'

.inverse
  background-color: base.$primary-color
  color: white

CSS Output

body {
  font: 100% Helvetica, sans-serif;
  color: #333;
}

.inverse {
  background-color: #333;
  color: white;
}








请注意,我们在 styles.scss 文件中使用 @use 'base';。使用文件时不需要包含文件扩展名。Sass 很聪明,会帮你解决的。

¥Notice we’re using @use 'base'; in the styles.scss file. When you use a file you don’t need to include the file extension. Sass is smart and will figure it out for you.


混入混入 permalink

¥Mixins

CSS 中的某些内容写起来有点乏味,尤其是使用 C 和存在的许多浏览器前缀。mixin 允许你创建要在整个站点中重复使用的 CSS 声明组。它有助于让你的 Sass 保持干燥。你甚至可以传递值以使你的 mixin 更加灵活。这是 theme 的示例。

¥Some things in CSS are a bit tedious to write, especially with CSS3 and the many vendor prefixes that exist. A mixin lets you make groups of CSS declarations that you want to reuse throughout your site. It helps keep your Sass very DRY. You can even pass in values to make your mixin more flexible. Here’s an example for theme.

Playground

SCSS Syntax

@mixin theme($theme: DarkGray) {
  background: $theme;
  box-shadow: 0 0 1px rgba($theme, .25);
  color: #fff;
}

.info {
  @include theme;
}
.alert {
  @include theme($theme: DarkRed);
}
.success {
  @include theme($theme: DarkGreen);
}


Playground

Sass Syntax

@mixin theme($theme: DarkGray)
  background: $theme
  box-shadow: 0 0 1px rgba($theme, .25)
  color: #fff

.info
  @include theme

.alert
  @include theme($theme: DarkRed)

.success
  @include theme($theme: DarkGreen)




CSS Output

.info {
  background: DarkGray;
  box-shadow: 0 0 1px rgba(169, 169, 169, 0.25);
  color: #fff;
}

.alert {
  background: DarkRed;
  box-shadow: 0 0 1px rgba(139, 0, 0, 0.25);
  color: #fff;
}

.success {
  background: DarkGreen;
  box-shadow: 0 0 1px rgba(0, 100, 0, 0.25);
  color: #fff;
}

要创建 mixin,你可以使用 @mixin 指令并为其命名。我们将 mixin 命名为 theme。我们还在括号内使用变量 $theme,这样我们就可以传入我们想要的任何内容的 theme。创建 mixin 后,你可以将其用作 CSS 声明,以 @include 开头,后跟 mixin 的名称。

¥To create a mixin you use the @mixin directive and give it a name. We’ve named our mixin theme. We’re also using the variable $theme inside the parentheses so we can pass in a theme of whatever we want. After you create your mixin, you can then use it as a CSS declaration starting with @include followed by the name of the mixin.


扩展/继承扩展/继承 permalink

¥Extend/Inheritance

使用 @extend 可以让你从一个选择器到另一个选择器共享一组 CSS 属性。在我们的示例中,我们将使用与扩展占位符类密切相关的另一个功能来创建一系列简单的错误、警告和成功消息传递。占位符类是一种特殊类型的类,仅在扩展时才打印,并且可以帮助保持编译后的 CSS 整洁。

¥Using @extend lets you share a set of CSS properties from one selector to another. In our example we’re going to create a simple series of messaging for errors, warnings and successes using another feature which goes hand in hand with extend, placeholder classes. A placeholder class is a special type of class that only prints when it is extended, and can help keep your compiled CSS neat and clean.

Playground

SCSS Syntax

/* This CSS will print because %message-shared is extended. */
%message-shared {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
}

// This CSS won't print because %equal-heights is never extended.
%equal-heights {
  display: flex;
  flex-wrap: wrap;
}

.message {
  @extend %message-shared;
}

.success {
  @extend %message-shared;
  border-color: green;
}

.error {
  @extend %message-shared;
  border-color: red;
}

.warning {
  @extend %message-shared;
  border-color: yellow;
}
Playground

Sass Syntax

/* This CSS will print because %message-shared is extended. */
%message-shared
  border: 1px solid #ccc
  padding: 10px
  color: #333

// This CSS won't print because %equal-heights is never extended.
%equal-heights
  display: flex
  flex-wrap: wrap

.message
  @extend %message-shared

.success
  @extend %message-shared
  border-color: green

.error
  @extend %message-shared
  border-color: red

.warning
  @extend %message-shared
  border-color: yellow






CSS Output

/* This CSS will print because %message-shared is extended. */
.warning, .error, .success, .message {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
}

.success {
  border-color: green;
}

.error {
  border-color: red;
}

.warning {
  border-color: yellow;
}













上面的代码的作用是告诉 .message.success.error.warning 的行为就像 %message-shared 一样。这意味着 %message-shared 出现的任何地方,.message.success.error.warning 也会出现。神奇的事情发生在生成的 CSS 中,其中每个类都将获得与 %message-shared 相同的 CSS 属性。这有助于你避免在 HTML 元素上编写多个类名。

¥What the above code does is tells .message, .success, .error, and .warning to behave just like %message-shared. That means anywhere that %message-shared shows up, .message, .success, .error, & .warning will too. The magic happens in the generated CSS, where each of these classes will get the same CSS properties as %message-shared. This helps you avoid having to write multiple class names on HTML elements.

除了 Sass 中的占位符类之外,你还可以扩展大多数简单的 CSS 选择器,但使用占位符是确保你不会扩展嵌套在样式中其他位置的类的最简单方法,这可能会导致 CSS 中出现意外的选择器。

¥You can extend most simple CSS selectors in addition to placeholder classes in Sass, but using placeholders is the easiest way to make sure you aren’t extending a class that’s nested elsewhere in your styles, which can result in unintended selectors in your CSS.

请注意,%equal-heights 中的 CSS 不会生成,因为 %equal-heights 永远不会扩展。

¥Note that the CSS in %equal-heights isn’t generated, because %equal-heights is never extended.


运算符运算符 permalink

¥Operators

CSS 中进行数学运算非常有帮助。Sass 有一些标准数学运算符,例如 +-*math.div()%。在我们的示例中,我们将进行一些简单的数学计算来计算 articleaside 的宽度。

¥Doing math in your CSS is very helpful. Sass has a handful of standard math operators like +, -, *, math.div(), and %. In our example we’re going to do some simple math to calculate widths for an article and aside.

Playground

SCSS Syntax

@use "sass:math";

.container {
  display: flex;
}

article[role="main"] {
  width: math.div(600px, 960px) * 100%;
}

aside[role="complementary"] {
  width: math.div(300px, 960px) * 100%;
  margin-left: auto;
}
Playground

Sass Syntax

@use "sass:math"

.container
  display: flex

article[role="main"]
  width: math.div(600px, 960px) * 100%

aside[role="complementary"]
  width: math.div(300px, 960px) * 100%
  margin-left: auto



CSS Output

.container {
  display: flex;
}

article[role=main] {
  width: 62.5%;
}

aside[role=complementary] {
  width: 31.25%;
  margin-left: auto;
}


我们创建了一个非常简单的基于 960px 的流体网格。Sass 中的操作让我们可以轻松地执行一些操作,例如获取像素值并将它们转换为百分比。

¥We’ve created a very simple fluid grid, based on 960px. Operations in Sass let us do something like take pixel values and convert them to percentages without much hassle.