Cài đặt:
- Cài Node.js
- Chạy lệnh npm install -g sass
Các ưu điểm của SCSS:
- SCSS dễ dàng làm quen và sử dụng(hỗ trợ 100% cú pháp của CSS và thêm 1 số khái niệm mới).
- Tiết kiệm thời gian viết CSS.
- Dễ dàng bảo trì và phát triển.
- Có tính linh hoạt và tái sử dụng cao.
- Các tập tin, đoạn mã CSS được tổ chức, sắp xếp một cách rõ ràng.
Các tính năng cơ bản của SCSS:
1.Có thể đặt biến và sử dụng biến
| SCSS | CSS |
| $primary: blue; $padding: 10px; .btn-primary { background: $primary; padding: $padding; } .text-primary { color: $primary; } |
.btn-primary { background: blue; padding: 10px; } .text-primary { color: blue; } |
2.Cho phép viết cú pháp lồng nhau(có thể lồng nhiều cấp nhưng tốt nhất khi nên ở 3 cấp)
| SCSS | CSS |
| .hello { color: red; .world { color: red; } } |
.hello { color: red; } .hello .world { color: red; } |
3.Có thể kế thừa
| SCSS | CSS |
| .btn { color: red; border: 1px solid #000; } .btn-default { @extend .btn; color: blue; } |
.btn, .btn-default { color: red; border: 1px solid #000; } .btn-default { color: blue; } |
4.Partials & Modules
| SCSS | CSS |
| // _base.scss $font-stack: Helvetica, sans-serif; $primary-color: #333; body { font: 100% $font-stack; color: $primary-color; } // styles.scss @use ‘base’;.inverse { background-color: base.$primary-color; color: white; } |
// styles.scss body { font: 100% Helvetica, sans-serif; color: #333; } .inverse { background-color: #333; color: white; } |
5.Hỗ trợ cú pháp mixin sử dụng lại code(tương tự như 1 function)
| SCSS | CSS |
| @mixin col ($width) { width: $width; float: left; padding-left: 10px; padding-right: 10px; } .col-6 { @include col(50%); } .col-12 { @include col(100%); } |
.col-6 { width: 50%; float: left; padding-left: 10px; padding-right: 10px; } .col-12 { width: 100%; float: left; padding-left: 10px; padding-right: 10px; } |
6.Áp dụng tính toán
| SCSS | CSS |
| article { float: left; width: 600px / 960px * 100%; } |
Compiled CSS article { float: left; width: 62.5%; } |
Cách sử dụng
Trong dự án sau khi đã tạo file .scss sử dụng câu lệnh sau để biên dịch thành css
Biên dịch thủ công
sass scss/input.scss css/output.css
scss/input.scsslà đường dẫn tới file .scss đã tạo.css/output.csslà file đường dẫn mà trình biên dịch sẽ tạo.
Tự động biên dịch 1 file .scss
Thêm cờ --watch
sass –watch input.scss output.css
Trình biên dịch sẽ tự động biên dịch file input.scss thành output.css sau khi lưu input.scss
Tự động biên dịch hàng loạt file .scss
sass –watch app/sass:app/css
app/scsslà đường dẫn chứa các file .scss đã tạo.app/csslà đường dẫn lưu các file css do trình biên dịch tạo.