SCSS - @extend vs @include


Posted by TempuraEngineer on 2022-04-17

@extend & @include

@extend @include
特點 共享 引入
搭配 @mixin
可帶參數
常用於 幾乎一樣的東西 重複使用的css


@extend例子

編譯前

    // 這樣做OK
    // 不過實務上如果要符合OOCSS的話其實&-danger和&-success都不用@extend .button
    // 只要再HTML寫 <button class="button button-danger"></button>即可

    .button{
        border-radius:4px;
        width:20px;
        color: white;    

        &-danger{
            @extend .button;
            background-color: firebrick;
        }

        &-success{
            @extend .button;
            background-color: green;
        }
    }

編譯後

    /* .button-danger和.button-success會與.button共享樣式 */

    .button, .button-danger, .button-success { 
        border-radius: 4px;
        width: 20px;
        color: white;
    }

    .button-danger {
        background-color: firebrick;
    }

    .button-success {
        background-color: green;
    }

@include例子

  • 搭配@mixin
    @mixin:把常用的css code用mixin包成一個模組。對於重複使用css很有用。
    編譯前

      @mixin button($width, $bg-color){
          border-radius:4px;
          width:$width;
          background-color: $bg-color;
          color: white;
      }
    
      .button-danger{
          @include button(20px, firebrick);
      }
    
      .button-success{
          @include button(20px, green);
      }
    

    編譯後

      /* .button-danger和.button-success都直接將模組引入,而不和其他class共享樣式 */
    
      /* 這樣雖然比較方便看,但違反OOCSS的減少重複的原則 */
      .button-danger {
          border-radius: 4px;
          width: 20px;
          background-color: firebrick;
          color: white;
      }
    
      .button-success {
          border-radius: 4px;
          width: 20px;
          background-color: green;
          color: white;
      }
    
  • 搭配@mixin 與 @for
    編譯前

      @mixin helper($property, $val){
          @for $i from 1 to length($property) + 1{
              #{nth($property, $i)}:nth($val, $i);
          }
      }
    
      .font-common{
          @include helper((font-size, font-family), (20px, arial));
      }
    
      .font-blue-bold{
          @include helper((color, font-weight, text-decoration), (blue, bold, underline));
      }
    

    編譯後

      .font-common {
        font-size: 20px;
        font-family: arial;
      }
    
      .font-blue-bold {
        color: blue;
        font-weight: bold;
        text-decoration: underline;
      }
    


📖

include vs extend
SASS official site


#SCSS







Related Posts

JavaScript 的同步與非同步 - 從 Callback function 到 Promise

JavaScript 的同步與非同步 - 從 Callback function 到 Promise

F2E合作社|共用項目margin與padding|Bootstrap 5網頁框架開發入門

F2E合作社|共用項目margin與padding|Bootstrap 5網頁框架開發入門

MTR04_0616

MTR04_0616


Comments