1. 程式人生 > 其它 >SASS使用方法環境配置 Ruby安裝以及sass常用mixins舉例 靜態頁使用方法

SASS使用方法環境配置 Ruby安裝以及sass常用mixins舉例 靜態頁使用方法

Sass介紹:

Sass 是一個 CSS 前處理器。是 CSS 擴充套件語言,可以幫助我們減少 CSS 重複的程式碼,節省開發時間並且完全相容所有版本的 CSS。
Sass 擴充套件了 CSS3,增加了規則、變數、混入、選擇器、繼承、內建函式等等特性。生成良好格式化的 CSS 程式碼,易於組織和維護。檔案字尾為 .scss

為什麼使用Scss?

CSS 本身語法不夠強大,導致重複編寫一些程式碼,無法實現複用,而且在程式碼也不方便維護。Sass 引入合理的樣式複用機制,增加了規則、變數、混入、選擇器、繼承、內建函式等等特性。

安裝與使用

1.使用Sass首先需要安裝Ruby然後再安裝Sass。Windows平臺安裝Ruby,官網下載地址
https://rubyinstaller.org/downloads/
去官網下載安裝包,下載之後安裝,Ruby安裝過程較為簡單,選好安裝位置直接下一步,預設選中安裝就可以
2.安裝完成之後去電腦裡搜尋以下內容開啟
3.在命令列中輸入命令gem install sass安裝sass,如果安裝成功輸入sass -v檢察是否安裝成功

基本用法

1.變數
// 宣告
$white:#FFFFFF;
$black:#000000;
//使用
div {
	width:100px;
	height:100px;
	background-color: $white;
	color:$black;
}

2.如果變數需要鑲嵌在字串之中,就必須需要寫在#{}之中。
$left : left;
.sides {
 margin-#{$left}: 5px;
}
3.樣式巢狀(Sass允許選擇器巢狀寫法,先看一段常規CSS程式碼:)
.fd-foot2 {
  height: 190px;
  width: 100%;
  min-width: 1300px;
  background: url("../img/foot.png") no-repeat;
  background-size: 100% 100%;
}

.fd-foot2 .fd-foot2-main {
  width: 1200px;
  margin: 0 auto;
  padding-top: 36px;
}

.fd-foot2 .fd-foot2-main p {
  font-size: 16px;
  color: #FFFFFF;
  line-height: 135px;
}
如果用sass寫,可以寫成一下程式碼:
// 底部footer
.fd-foot2 {
	height: 190px;
	width: 100%;
	min-width: 1300px;
	background: url('../img/foot.png') no-repeat;
	background-size: 100% 100%;
  .fd-foot2-main {
    width: 1200px;
    margin: 0 auto;
    padding-top: 36px;
    p {
      font-size: 16px;
      color: $white;
      line-height: 135px;
    }
  }
}
在巢狀的程式碼塊內,可以使用&引用父元素。比如a:hover偽類,可以寫成:
a {
  &:hover { color: #ffb3ff; }
}
4.具有計算功能
.examples {
	position:absolute;
	left: (50px/2);
  top: 50px + 100px;
  right: $var * 10%;
}
5.繼承(程式碼的重用)
.fd-hqqd-left-bottom1-2 {
  width:100px;
  height:100px;
  margin-right: 10px;
}
.fd-hqqd-left-bottom1-1 {
  @extend .fd-hqqd-left-bottom1-2;
  margin-bottom: 10px;
}
6.Mixin可以重用程式碼塊,使用mixin命令定義一個程式碼塊
@mixin widthHeight($widthValue:100px,$heightValue:100px) {
  width: $widthValue;
	height: $heightValue;
}
使用@include命令,掉用這個mixin
.fd-hqqd-left-bottom1-2 {
  @include widthHeight(235px,172.6px);
  margin-right: 10px;
}
7.條件語句可以使用@if @else來進行判斷
@mixin positionAbsolute($top:null,$right:null,$bottom:null,$left:null) {
  position: absolute;
  @if ($left!="" & & $left!=null) {
    left: $left;
  }
  @if ($right!="" & & $right!=null) {
    right: $right;
  }
  @if ($top!="" & & $top!=null) {
    top: $top;
  }
  @if ($bottom!="" & & $bottom!=null) {
    bottom: $bottom;
  }
}
8.迴圈語句
1.for
@for $i from 1 to 10 {
    .border-#{$i} {
      border: #{$i}px solid blue;
    }
  }
  2.while
 $i: 6;

  @while $i > 0 {
    .item-#{$i} { width: 2em * $i; }
    $i: $i - 2;
  }
  3.each
 @each $member in a, b, c, d {
    .#{$member} {
      background-image: url("/image/#{$member}.jpg");
    }
  }
9.sass檔案的插入,可以使用@import命令來插入外部檔案

@import './mixin.scss';

靜態介面中使用scss(vscode外掛推薦)

安裝好兩個外掛之後,修改scss檔案之前點選一下Watch Sass
在scss檔案裡點選儲存的時候,就會自動生成css檔案