Sass / Scss 入門

講者:鄒適齊(Rex Tsou)

講綱

  • Sass/Scss 是什麼 >>
  • 編譯!? >>
  • 安排檔案架構 >>
  • 基礎語法介紹 >>
  • 實作示範與練習時間 >>
  • 小作業 >>
  • 參考資料與學習資源 >>

Sass/SCSS 是什麼

Official Site: sass-lang.com

  1. Dart Sass
  2. LibSass* ➡ node-sass
  3. Ruby Sass

CSS 的超集(superset)

  • 檔名為 *.scss
  • 編譯成 CSS 瀏覽器才看得懂
  • 為了開發與管理(ex: 巢狀、變數、分檔)
  • 可配合函式庫使用(Compass、Bourbon

在 CSS 的基礎上增加功能,由於是超集,在 SCSS 內可以直接寫 CSS,不會有錯誤(舊專案直接把 *.css 改成 *.scss 就可以了)

Sass vs. SCSS

Syntactically Awesome StyleSheets


          .block
            width: 600px
            height: 300px
            .text
              color: red
          

Sassy CSS (Sass version 3)


          .card {
            background: #EFEFEF;
            .title {
              font-size: 1.2em;
            }
          }
          

編譯!?

編譯(compile)是什麼?

其實就是翻譯

原始語言(便於編寫與閱讀)

目標語言(電腦執行效率高)

編譯環境建置:懶人包

先安裝 docker(macwindows

然後依照這個專案的說明來使用

編譯環境建置:詳解

Gulp

自動化建置工具


            // 設定檔範例:gulpfile.js
            gulp.task('css', () => {
              gulp.src('src/sass/**/*.scss')
                .pipe($.plumber())
                .pipe($.sass.sync({
                  outputStyle: 'nested', // expanded, nested, compact, compressed
                  precision: 10,
                  includePath: ['.'],
                }).on('error', $.sass.logError))
                .pipe($.autoprefixer({ browsers: ['last 2 versions'] }))
                .pipe(gulp.dest('dist/css')) // output folder
                .pipe(browserSync.stream())
                .pipe($.notify("Compile Sass Complete!"))
            });
          

GUI 介面 vs. CLI 介面
(大部分前端工程師使用 CLI,因為容易調整設定,且可以配合其他工具使用)

GUI 介面

  • CodeKit (paid)
  • Compass.app (paid, open source)
  • Ghostlab (paid)
  • Hammer (paid)
  • Koala (open source)
  • LiveReload (paid, open source)
  • Prepros (paid)*
  • Scout-App (free, open source)

CLI 介面

  • 直接用 sass cli
    
                  # terminal
                  sass in.scss out.css
                  
  • 用自動化建置工具
    • Gulp*
    • Webpack

安排檔案架構


            // your project folder
            // src/sass => dist/css
            .
            ├── README.md
            ├── dist
            │   ├── assets
            │   │   ├── backgrounds
            │   │   ├── icon
            │   │   └── materials
            │   ├── css
            │   │   ├── layout
            │   │   │   ├── about.css
            │   │   │   ├── contact.css
            │   │   │   └── index.css
            │   │   └── main.css
            │   ├── index.html
            │   ├── js
            │   │   └── bundle.js
            │   ├── module
            │   │   └── card-case.html
            │   └── partial
            │       ├── default-script.html
            │       ├── footer.html
            │       └── head.html
            ├── gulpfile.babel.js
            ├── index.html
            ├── package-lock.json
            ├── package.json
            └── src
                ├── assets
                │   ├── backgrounds
                │   ├── icon
                │   └── materials
                ├── js
                │   ├── main.js
                │   └── utils
                │       ├── index.js
                │       └── toggle-active.js
                ├── sass
                │   ├── _base.scss
                │   ├── _font.scss
                │   ├── _variable.scss
                │   ├── layout // 分頁面
                │   │   ├── about.scss
                │   │   ├── contact.scss
                │   │   └── index.scss
                │   ├── main.scss
                │   ├── mixin // 共用常用的邏輯
                │   │   ├── _assets.scss
                │   │   ├── _breakpoint.scss
                │   │   └── _mixins.scss
                │   ├── module // 模組化的元件
                │   │   ├── _card-case.scss
                │   │   ├── _developing.scss
                │   │   ├── _footer.scss
                │   │   ├── _header.scss
                │   │   └── _mask.scss
                │   └── vendor // 第三方套件
                │       └── normalize-scss
                └── views
                    ├── index.pug
                    ├── module
                    │   └── card-case.pug
                    └── partial
                        ├── default-script.pug
                        ├── footer.pug
                        └── head.pug

          

7-1 pattern

gist: sass-7-1-pattern.scss

基礎語法

註解

            // 我是單行註解,編譯後就不見了

            /* 我是多行註解
            而且編譯後還會在 */
            
...

            /* 我是多行註解
            而且編譯後還會在 */
            
變數

用 $ 開頭即為變數,先定義後使用。


            $color--red: #F55; // 定義紅色
            $color--blue: #55F; // 定義藍色

            .text {
              color: $color--red;
              border: $color--blue;
            }
            
...

            .text {
              color: #F55;
              border: #55F;
            }
            
變數

注意 scope(區域變數、全域變數)


            .cute-box {
              $width: 300px; // 區域變數,作用範圍僅有括號內
              $height: 300px !global; // 全域
              width: $width;
            }
            .another-box {
              width: $width; // 這樣是拿不到的
              height: $height; // 這樣可以
            }
            
運算子
- 比較運算:`==`, `!=`, `<`, `>`, `<=`, `>=` - 數學運算:`+`, `-`, `*`, `/`, `%` ---
舉個栗子🌰:
``` p { $width: 1000px; width: $width/2; // 500px $font-size: 12px; $ling-height: 30px; // 必須用 #{} 插值,避免純 css 的 / 被當成除法 font: #{$font-size}/#{$line-height}; // 這不是運算 XD } ```
運算子
特別的運算:顏色
``` p { color: #010203 + #040506; // #050709 color: #010203 * 2; // #020406 color: rgba(255, 0, 0, .75) + rgba(0, 255, 0, .75); // rgba(255, 255, 0, .75) } ``` 也可以運用內建函式進行運算( HSL!混色!相反色!),屬於進階應用,有興趣再介紹
重要的 &

代表當前的上層選擇器 ``` // scss a { font-weight: bold; &:hover { opacity: .7; } } ``` ... ``` // css a { font-weight: bold; } a:hover { opacity: .7; } ```
重要的 & 需要兩張投影片
``` // scss .main { color: #333; a { border-bottom: 1px dashed #33d; &:hover { color: red; } } } ```
其實還有第三張
``` // 配合 BEM 等 CSS 架構使用有奇效 .main { &--left { background: #555; } &--right { background: #777; } } ```
%(placeholder)和 @extend
``` // 如果偏向 Modular CSS 的架構,應該比較少用 %normal-box { width: 100px; height: 100px; } .box-red { @extend %normal-box; background: red; } .box-blue { @extend %normal-box; background: blue; } ```
@mixin 和 @include
``` // 可以想像成製造 box 的機器 @mixin box($width, $height, $background) { width: $width; height: $height; background-color: $background; } .red-box { @include box(100px, 100px, #f00); } .blue-box { @include box(100px, 100px, #00f); } ```
@mixin 和 @include
``` // 以前很多人會這樣利用 @mixin @mixin rounded-corners($tl : 4px, $tr : 4px, $br: 4px, $bl: 4px) { -webkit-border-radius:$tl $tr $br $bl; -moz-border-radius:$tl $tr $br $bl; -o-border-radius:$tl $tr $br $bl; border-radius:$tl $tr $br $bl; } .special-corner { @include rounded-corners(0, 0, 10px, 10px); } ```

@-rules

@import
``` // 以下幾種情形會有不同結果 @import "foo.scss"; // include @import "foo"; // include @import "foo.css"; @import "foo" screen; @import "https://foo.com/bar"; @import url(foo); ```

@-rules

@media
可以寫成巢狀(寫 RWD 很方便) ```scss // 以下是 mobile first 寫法 .sidebar { width: 300px; // 手機 @media (min-width: 600px) { width: 500px; // 平板(portrait) } @media (min-width: 900px) { width: 600px; // 平板(landscape) } @media (min-width: 1200px) { width: 800px; // 桌面 } } ```

補充:資料型態

資料型態

主要有 8 種資料型態,不需要死記

  • number
    
                      1.2
                      13
                      10px
                    
  • string
    
                      "foo"
                      'bar'
                      baz
                    
資料型態
  • color
    
                      blue
                      #04a3f9
                      rgba(255, 0, 0, 0.5)
                    
  • boolean
    
                      true
                      false
                    
  • null
    
                      null
                    
資料型態
  • list
    
                      1.5em 1em 0 2em // 用空格分隔
                      Helvetica, Arial, sans-serif // 或用逗號分隔
                    
  • map
    
                      (key1: value1, key2: value2)
                    
  • function reference

課堂實作

小作業

如果覺得不夠...

參考資料

- [Sass/SCSS 簡明入門教學](https://blog.techbridge.cc/2017/06/30/sass-scss-tutorial-introduction/) - [建立 Sass 環境](https://www.slideshare.net/chihchengwang3/sass-node-sass) - [Sass Guidelines](https://sass-guidelin.es/) - [Sass color maps](https://gist.github.com/akccakcctw/afdd74914e0b2d6b28ed815030da9f22) - [Gulp for beginners](https://css-tricks.com/gulp-for-beginners/)

延伸閱讀:CSS 設計模式

- [撰寫可管理、可維護的 CSS 高階技巧](https://github.com/doggy8088/CSS-Guidelines) - [Medium’s CSS is actually pretty f***ing good](https://medium.com/@fat/mediums-css-is-actually-pretty-fucking-good-b8e2a6c78b06) - [CSS-TRICKS: BEM 101](https://css-tricks.com/bem-101/) - [css architecture for design systems](http://bradfrost.com/blog/post/css-architecture-for-design-systems/) - [Should You Chain or Extend CSS Classes?](https://frontstuff.io/should-you-chain-or-extend-css-classes)