LoginSignup
202
168

More than 5 years have passed since last update.

[SCSS]便利な&(アンパサンド)の使い方メモ

Last updated at Posted at 2018-03-03

SCSSにおいての&(アンパサンド)の使い方備忘録です。

基本の使い方

.class {
    &.hoge {
        background-color : #31A0FF;
    }

    &__foo {
        background-color: #FD997C;
    }

    &:hover {
        text-decoration: underline;
    }
}

コンパイル後のCSS

.class.hoge {
  background-color: #31A0FF;
}

.class__foo {
  background-color: #FD997C;
}

.class:hover {
  text-decoration: underline;
}

シンプルに.classの直後に&後の文字列がくっつきます。

&を組み合わせる

.class {
    & + & {
        margin-top: 1em;
    }

    &,
    &--hoge {
        margin-top: 1em;
    }
}

コンパイル後のCSS

.class + .class {
  margin-top: 1em;
}

.class, .class--hoge {
  margin-left: 1em;
}

特定の親要素の場合に適用

.class {
    color: #333;

    .parent & { // 親要素指定
        color: #8B5BB5;
    }

    .parent &__foo { // 親要素+class名変化
        color: #3B8C10;
    }
}

コンパイル後のCSS

.class {
  color: #333;
}

.parent .class {
  color: #8B5BB5;
}

.parent .class__foo {
  color: #3B8C10;
}

.class の中でも.parent内の.classにだけ適用したい時に便利です。

特定の親要素の応用

.class {
    $parent: &; // 親要素を変数に定義

    &__child {
        color: #333;

        #{$parent} & { // 親要素を変数で呼び出し
            color: #8B5BB5;
        }

        #{$parent}-hoge & { // 親要素を変数+class名変化で呼び出し
            color: #3B8C10;
        }
    }
}

コンパイル後のCSS

.class__child {
  color: #333;
}

.class .class__child {
  color: #8B5BB5;
}

.class-hoge .class__child {
  color: #3B8C10;
}

親要素のclass名を変化させられるのは便利ですね!
$hoge : &;これで変数に定義できるというのも驚きです。

@at-rootと組み合わせてルートから指定

@at-root 基本

@at-root を先頭につけると、階層を無視してコンパイルされます。

.parent {
    @at-root .class {
        display: flex;
    }
}

コンパイル後のCSS

.class {
  display: flex;
}

親要素の.parentを無視して.classが独立します。

@at-root と & の組み合わせ

@at-root はあまり使う機会はありませんが、&と組み合わせるとブラウザハックなどに便利です。

.class {
    display: flex;

    // IE10以降のハック
    @at-root _:-ms-input-placeholder, :root & {
        display: block;
    }
}

コンパイル後のCSS

.class {
  display: flex;
}

_:-ms-input-placeholder, :root .class {
  display: block;
}

以上になります。

プリプロセッサーで書く方法を覚えてしまうとCSS直書きには戻れませんね。

お役に立てたら幸いです。


下記のページを参考にさせていただきました。ありがとうございます。

▼Level up your Sass with the ampersand
https://codepen.io/hidanielle/post/level-up-your-sass-with-the-ampersand

202
168
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
202
168