为什么在 SCSS 文件名前加“_”?
SCSS 允许开发者以更结构化的方式编写 CSS。此外,使用 SCSS 时,我们可以为 CSS 创建多个文件,并在主 SCSS 文件中导入所需文件。
在本教程中,我们将了解在 SCSS 文件名前添加“_”的目的。
什么时候应该在 SCSS 文件名前添加“_”?
当我们在 SCSS 文件名前添加“_”时,编译器在编译 SCSS 时会忽略该文件。如果文件名以“_”字符开头,则该文件将成为局部文件。
例如,我们有两个名为“style.scss”和“_partial.scss”的文件。编译器只编译 style.scss 文件,而忽略 _partial.scss 文件。但是,如果我们需要使用 _partial.scss 文件的 CSS,我们可以在 style.scss 文件中导入它。
示例
下面的示例演示了如何在 HTML 中使用 SCSS。
文件名 – demo.html
我们使用``标签在下面的文件中添加了一个“style.css”文件,该文件是由 SCSS 编译器生成的。在输出中,用户可以看到 CSS 应用于 div 元素的文本,文本变成了斜体。
<html> <head> <link rel = "stylesheet" href = "style.css"> </head> <body> <h2> Using the <i> SCSS </i> with HTML. </h2> <div> This is a div element. </div> </body> </html>
文件名 – style.scss
在下面的文件中,我们创建了变量来存储字体大小和样式。然后,我们使用这些变量来设置 div 元素的样式。
$font-size : 20px;
$font-style: italic;
div {
font-size: $font-size;
font-style: $font-style;
}
文件名 – style.css
每当我们编译 style.scss 文件时,它都会生成下面的代码,该代码由 html 文件使用。
div {
font-size: 20px;
font-style: italic;
}
示例
<html>
<head>
<style>
/* compiled scss code */
div {
font-size: 20px;
font-style: italic;
}
</style>
</head>
<body>
<h2> Using the <i> SCSS </i> with HTML. </h2>
<div> This is a div element. </div>
</body>
</html>
示例
在这个例子中,我们演示了如何在文件名之前添加“_”,以及如何在主 css 文件中使用它的 CSS。
文件名 – demo.html
下面的文件包含简单的 HTML 代码,并在`
`标签中包含了“style.css”文件。<html> <head> <link rel = "stylesheet" href = "style.css"> </head> <body> <h2> Using the <i> SCSS from the _partial.css file </i> with HTML.</h2> <div> Content of the div element. </div> </body> </html>
文件名 - _partial.scss
用户需要创建一个文件名以“_”开头的 _partial.scss 文件。然后,用户需要在文件中添加以下代码。当我们编译 SCSS 代码时,编译器将忽略此文件中的代码。
$text-color: blue; $border-width: 2px; $border-style: solid; $border-color: green;
文件名 – style.scss
现在,用户需要将以下代码添加到 style.scss 文件中,这是主 css 文件。在下面的代码中,我们从“_partial.scss”文件导入了 css。通过这种方式,我们可以使用局部文件的代码。
@import "partial"
div {
color: $text-color;
border: $border-width $border-style $border-color;
}
文件名 – style.css
每当我们编译 style.scss 文件时,它都会自动生成 style.css 文件。
div {
color: blue;
border: 2px solid green;
}
示例
<html>
<head>
<style>
/* compiled SCSS code from the _partial.css file */
div {
color: blue;
border: 2px solid green;
}
</style>
</head>
<body>
<h2> Using the <i> SCSS from the _partial.css file </i> with HTML.</h2>
<div> Content of the div element. </div>
</body>
</html>
在 SCSS 文件名前插入“_”的主要目的是使文件成为局部文件,以便编译器可以忽略该文件。每当我们需要使用局部文件的 CSS 时,我们都可以将其导入主文件。
使用局部文件的主要好处是,我们不需要编写重复的代码,使代码更清晰。例如,我们可以为不同部分的 CSS 添加不同的局部文件,并在需要时使用它们。
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP