# Scss 迴圈計算式
###### tags: `SCSS` `React`
### 前言
#### 因為使用Core UI React元件 ,建立在bootstrap上的UI框架,眾所皆知bootstrap框架是一個可以快速使用但要精細調整class會不太夠使用.
#### Core UI 有一點還不錯的是,在斷點擴充了xxl 和 xs ,共有xs、sm、md、lg、xl、xxl ,在大螢幕和小螢幕間比原本bootstrap更細膩,但就是這個but ,很多mt,ml,mr,pt,flex-wrap....等等沒有做xxl和xs.
#### 所以就去scss檔設定,但手動一個個加入覺得實在很累
```
@media (max-width:576px) {
.ml-xs-n1
margin-left: -0.5rem;
}
.ml-xs-n2{
margin-left: -1rem;
}
.ml-xs-n3{
margin-left: -1.5rem;
}
.ml-xs-n4{
margin-left: -2rem;
}
.ml-xs-n5{
margin-left: -2.5rem;
}
}
```
#### 所以研究可否跑回圈帶公式自動跑出來,google一下找到有大大分享
[SCSS 那些年我們一起跑的迴圈](https://timchen0607.medium.com/scss-%E9%82%A3%E4%BA%9B%E5%B9%B4%E6%88%91%E5%80%91%E4%B8%80%E8%B5%B7%E8%B7%91%E7%9A%84%E8%BF%B4%E5%9C%88-c366984fc7f0)
### scss斷點設定方式
@mixin name {
@media (min-width:576px){
@content
}
}
name為任一個你想要設定的名稱 , @content為css內容
### 迴圈變數
$ max 為要設定迴圈跑數量 , 比如我門想要設定<kbd> ml-xs-1 </kbd> ~ <kbd>ml-xs-10</kbd>
那麼是 **$max:10**
**i** 為代表 class - * , *的這個變數
**@for i from <start> through <end> { }**
$max:10;
@for $i from 0 through $max
編譯出來為 *-1 ~ *-10
**throught** 概念為 <kbd>>=</kbd>
**@for i from <start> to <end> { }**
$max:10;
@for $i from 0 to $max
編譯出來為 *-1 ~ *-9
**to** 概念為 <kbd> <= </kbd>
### 來試試 576px以下 ml-xs-n1 ;$max:5; @for $i from 0 through $max 會帶出怎樣結果吧?
使用[scss to css](https://jsonformatter.org/scss-to-css) 線上編譯網站
```
@mixin xs {
@media (min-width:576px){
@content
}
}
$max:5;
@for $i from 0 through $max {
@include xs{
.ml-xs-n#{$i} {
margin-left:($i) * 0.5rem!important;
}
}
}
```
帶出來的結果會是
```
@media (min-width: 576px) {
.ml-xs-n0 {
margin-left: 0rem !important;
}
}
@media (min-width: 576px) {
.ml-xs-n1 {
margin-left: 0.5rem !important;
}
}
@media (min-width: 576px) {
.ml-xs-n2 {
margin-left: 1rem !important;
}
}
@media (min-width: 576px) {
.ml-xs-n3 {
margin-left: 1.5rem !important;
}
}
@media (min-width: 576px) {
.ml-xs-n4 {
margin-left: 2rem !important;
}
}
@media (min-width: 576px) {
.ml-xs-n5 {
margin-left: 2.5rem !important;
}
}
```
### 來試試 576px以下 ml-xs-1 ;$max:5; @for $i from 0 to $max 會帶出怎樣結果吧?
使用[scss to css](https://jsonformatter.org/scss-to-css) 線上編譯網站
```
@mixin xs {
@media (min-width:576px){
@content
}
}
$max:10;
@for $i from 1 to $max {
@include xs{
.ml-xs-#{$i} {
margin-left:($i) * 0.5rem!important;
}
}
}
```
帶出來的結果會是
```
@media (min-width: 576px) {
.ml-xs-0 {
margin-left: 0rem !important;
}
}
@media (min-width: 576px) {
.ml-xs-1 {
margin-left: 0.5rem !important;
}
}
@media (min-width: 576px) {
.ml-xs-2 {
margin-left: 1rem !important;
}
}
@media (min-width: 576px) {
.ml-xs-3 {
margin-left: 1.5rem !important;
}
}
@media (min-width: 576px) {
.ml-xs-4 {
margin-left: 2rem !important;
}
}
```