# 認識 Scss 與 Sass 寫法 ###### tags: `CSS` `SCSS` `SASS` `prepros` ## 環境安裝 1. 準備 Scss / Sass 的編譯環境 → [prepros](https://prepros.io/) 軟體安裝。 1. 進入網站後,點擊 "Download Free Unlimited Trial" 按鈕,安裝完成啟動 prepros。 1. 將開發檔案夾以滑鼠點擊拖入 prepros,prepros 即開始監測開發中的檔案。 1. 新增 .scss 或 .sass 檔案,開始撰寫。 1. 存檔後 prepros 會自動編譯出對應的 CSS 檔。 1. 如果編譯出現錯誤時,會在 prepros 出現提示。 ## Scss vs. Sass * Sass & Scss 皆需經編譯轉為 → CSS。 * 利用巢狀寫法(Nesting)減少重工負擔。 * CSS 巢狀不要超過四層。 ## Scss 寫法 * 寫法與 CSS 接近,選擇器需使用括號與分號。 * 選擇器可精簡寫在最外層,當選擇其以下階層,直接寫在大括弧內。 * Scss 可完全當作 CSS 來寫 scss ```Scss= .header { width: 50px; height: 50px; background: #000; ul{ width: 50px; } li{ height: 30px; a{ color: #000; } } } ``` 自動編譯產生對應 CSS ```css= .header { width: 50px; height: 50px; background: #000; } .header ul { width: 50px; } .header li { height: 30px; } .header li a { color: #000; } ``` ## Sass 寫法 * 不用括弧及分號。 * 以「縮排」表示階層 (一個縮排:2 個空白 or 1 個 tab)。 Sass ```sass= .header width: 50px height: 100px ul width: 100px li height: 100px color: #000 a color: pink ``` 自動編譯產生對應 CSS ```css= .header { width: 50px; height: 100px; } .header ul { width: 100px; } .header li { height: 100px; color: #000; } .header li a { color: pink; } ``` ## 變數 * 使用 $ 符號自訂變數與值。 * 整合相同設定,建立模組化管理。 * 補充用法: 常用顏色變數功能 darken($blue,10%) → 將變數色系調暗10% lighten (#ff0000,10%) → 將色碼色系調亮10% ```Scss= // color $primary: #428bca; $success: #5cb85c; $info: #5bc0de; $warning: #f0ad4e; $danger: #d9534f; $light: #fff; // font-size $font-m: 18px; $font-l: $font-m * 1.2; $font-s: $font-m * 0.8; // 使用自訂變數 .header { background: $primary; color: $light; h1 { font-size: $font-l; } } ``` ## @mixin * 使用 @mixin:將常用語法化簡為自己的知識庫。 * 使用 @include:引入 @mixin 功能。 ```Scss= // 自訂工具命名 hide-text @mixin hide-text { text-indent: 101%; white-space: nowrap; overflow: hidden; } // 引用 hide-text .logo { background: #555; @include hide-text; } ``` ## @import(匯入) * 可將 Scss 檔案彙整成一支 CSS 檔 * Scss 結構循序漸進優化網頁架構。 * 拆檔:每支 Sass 檔專心做一件事。 * 不急著想要一口氣到位,而是由一次一次專案累積起來,隨著經驗讓結構越來越嚴謹且完整! 參考結構 ```css= @import "variable"; // 所有全域變數 @import "mixin"; // 所有mixin @import "reset"; // reset.css @import "layout"; // 共同框架,第一層 @import "module"; // button,form,table @import "index"; // 首頁 @import "page1、page2"; // 內頁 ``` ## @mixin+@content(設計響應式設計) * 獨立一支"_grid.scss"檔案 * 使用 @content:可於後續用 @include 引入 @mixin 功能時,代表內容。 ```css= @mixin desktop { @media (max-width: 1280px) { @content } } @mixin desktop-top { @media (max-width: 1023px) { @content } } @mixin desktop-below { @media (max-width: 1024px) { @content } } @mixin pad { @media (max-width: 767px) { @content } } @mixin iphone { @media (max-width: 568px) { @content } } @mixin mobile480 { @media (max-width: 480px) { @content } } @mixin iphone5 { @media (max-width: 320px) { @content } } // 引入的寫法 .header { width: 100px; height: 100px; @include pad(){ height: auto; } @include iphone5(){ height: 30px; } a{ color: #000; @include iphone5(){ display: none; } } }