iT邦幫忙

2021 iThome 鐵人賽

DAY 17
0
Modern Web

使用SASS(SCSS)建立自己的CSS Library系列 第 17

[Day 17] Sass - Parent Selector

&
父選擇器“&”通常與Sass的Nesting用法搭配使用,
當內層的選擇器使用"&"時,它會替換為外層的選擇器。
舉個簡單的例子

.title {
  &.editing {
      font-weight: bold
  }
}

css為

.title .editing {
    font-weight: bold
}

“&” 還可以更靈活的運用於:

.alert {
  // 幫外層選擇器添加偽類(如hover、focus等等)
  &:hover {
    font-weight: bold;
  }

  // 也可以用來代替外層的字串
  [dir=rtl] & {
    margin-left: 0;
    margin-right: 10px;
  }

  // 甚至把它用來代替偽類的參數
  :not(&) {
    opacity: 0.8;
  }
}

編譯出的css為

.alert:hover {
  font-weight: bold;
}
[dir=rtl] .alert {
  margin-left: 0;
  margin-right: 10px;
}
:not(.alert) {
  opacity: 0.8;
}

有時候,會遇到一些比較長的名稱
(像是.accordion、.accordion__copy、.accordion__copy--open),
也可以用"&"來幫忙~
假如我們想得到這樣的css:

.accordion {
  max-width: 600px;
  margin: 4rem auto;
  width: 90%;
  font-family: "Raleway", sans-serif;
  background: #f4f4f4;
}
.accordion__copy {
  display: none;
  padding: 1rem 1.5rem 2rem 1.5rem;
  color: gray;
  line-height: 1.6;
  font-size: 14px;
  font-weight: 500;
}
.accordion__copy--open {
  display: block;
}

就可以用這樣的Scss來表示:

.accordion {
  max-width: 600px;
  margin: 4rem auto;
  width: 90%;
  font-family: "Raleway", sans-serif;
  background: #f4f4f4;

  &__copy {
    display: none;
    padding: 1rem 1.5rem 2rem 1.5rem;
    color: gray;
    line-height: 1.6;
    font-size: 14px;
    font-weight: 500;

    &--open {
      display: block;
    }
  }
}

參考資料:
https://sass-lang.com/documentation/style-rules/parent-selector


上一篇
[Day 16] Sass - Booleans
下一篇
[Day 18] Sass - Mixins
系列文
使用SASS(SCSS)建立自己的CSS Library21
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言