非常好用的CSS預處理器-SCSS
2024-04-23 06:00
前言
在前端的世界裡 CSS 是必不可少的,因為 CSS 用來實做使用者介面(UI),但在越來越大的專案中,單純的 CSS 已經不夠用了,這時候就需要 SCSS 來讓專案變的更簡潔、維護性更強等,下面會介紹 SCSS 優點及寫法。
變數
可以使用 $
字號來宣告變數,來達到重複使用且統一管理的目的。
scss1$primary-color: #007aff; 2$primary-border-radius: 8px; 3 4button { 5 color: $primary-color; 6 border-radius: $primary-border-radius; 7}
巢狀結構
巢狀結構可讓代碼看起來更簡潔且可讀性更強外,還可以使用&
來引用父選擇器,以下是兩個一樣的做法但分別使用 CSS 和 SCSS。
css1button { 2 width: 100px; 3} 4 5button span { 6 font-size: 16px; 7} 8 9button span:hover { 10 color: red; 11}
scss1button { 2 width: 100px; 3 4 span { 5 font-size: 16px; 6 7 &:hover { 8 color: red; 9 } 10 } 11}
這樣就能很清楚的知道 span 是在 button 裡面,且 span 在 hover 時 color 要做改變。
@extend 和 @mixin
兩者主要的目的都是讓 class 可以重複使用,差別只在於兩者編譯後的 CSS 以及**@mixin** 可以引入變數。
@extend 編譯成 css
scss1%common-button { 2 width: 100%; 3 font-size: 16px; 4} 5 6.button-1 { 7 @extend %common-button; 8} 9 10.button-2 { 11 @extend %common-button; 12}
編譯後:
css1.button-1, 2.button-2 { 3 width: 100%; 4 font-size: 16px; 5}
@mixin 編譯成 css
scss1@mixin common-button { 2 width: 100%; 3 font-size: 16px; 4} 5 6.button-1 { 7 @include common-button; 8} 9 10.button-2 { 11 @include common-button; 12}
編譯後:
css1.button-1 { 2 width: 100%; 3 font-size: 16px; 4} 5 6.button-2 { 7 width: 100%; 8 font-size: 16px; 9}
@mixin 傳入變數
scss1@mixin common-button($font-size) { 2 width: 100%; 3 font-size: $font-size; 4} 5 6.button-1 { 7 @include common-button(20px); 8} 9 10.button-2 { 11 @include common-button(16px); 12}
按照上面三個案例來說,如果不需要使用變數就用**@extend**,反之就使用**@mixin**,但在一些情況下**@extend** 是無法使用的,例如在**@media** 中是無法使用**@extend**,雖然**@mixin** 在編譯後會增加 css 的代碼量,但這並不會對用戶的下載量有太大的影響,所以我個人是推薦使用**@mixin** 即可。
最後
以上是SCSS裡我最常用的功能,當然SCSS還有其他的功能,但為了不讓文章篇幅太長就先介紹到這邊,希望能幫助到有需要的人,我們下次見~