首頁  >  文章  >  web前端  >  為什麼SCSS中檔名前面要加“_”?

為什麼SCSS中檔名前面要加“_”?

WBOY
WBOY轉載
2023-08-25 14:09:131223瀏覽

為什麼SCSS中檔名前面要加“_”?

SCSS 允許開發人員以更結構化的方式編寫 CSS。另外,我們可以在使用SCSS時為CSS建立多個文件,並將所需的文件匯入到主SCSS文件中。

在本教學中,我們將看到在 SCSS 中的檔案名稱前面加上「_」的目標。

什麼時候應該在 SCSS 中將「_」放在檔案名稱前面?

每當我們在 SCSS 中的檔案名稱之前加入 -_' 時,編譯器在編譯 SCSS 時都會忽略該檔案。如果檔案名稱以「_」字元開頭,則該檔案將變為部分檔案。

例如,我們有兩個名為「style.scss」和「_partial.scss」的檔案。編譯器僅編譯 style.scss 文件,忽略 _partial.scss 檔案。但是,如果我們需要使用_partial.scss檔案的css,我們可以將其匯入到style.scss檔案中。

範例

下面的範例示範如何將 SCSS 與 html 結合使用。

檔名 – 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.css

#使用者需要建立一個_partial.scss文件,文件名稱前面有「_」。之後,用戶需要在文件中加入以下程式碼。當我們編譯SCSS程式碼時,編譯器會忽略這個檔案的程式碼

$text-color: blue;
$border-width: 2px;
$border-style: solid;
$border-color: green;

檔名 – style.scss

現在,使用者需要將以下程式碼加入 style.scss 檔案中,該檔案是主 css 檔案。在下面的程式碼中,我們從「_partial.css」檔案匯入了 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添加不同的部分文件,並在需要時使用它們。

以上是為什麼SCSS中檔名前面要加“_”?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除