エンジニアのひよこ_level10

毎日更新してた人。たまに記事書きます。

sassでextendを使ってcssの継承をする【129日目】

こんな場面に有効

.button1 {
    width: 20px;
    height: 15px;
    background-color: red;
}

.button2 {
    width: 20px;
    height: 15px;
    background-color: blue;
}

解決方法2つ

.button {
    width: 20px;
    height: 15px;
}

.button1 {
    background-color: red;
}

.button2 {
    background-color: blue;
}

ってして、クラスを2つつける。

.button {
    width: 20px;
    height: 15px;
}

.button1 {
    @extend .button;
    background-color: red;
}

.button2 {
    @extend .button;
    background-color: blue;
}

結果

ボタンのデザインを変える時に、一箇所変えれば済むようになる。

継承なので、もう少しいい例があったかもしれないけど、便利なのは間違いない。

ちなみに後者のコンパイル結果は以下

.button, .button1, .button2 {
  width: 20px;
  height: 15px;
}

.button1 {
  background-color: red;
}

.button2 {
  background-color: blue;
}