通常通りSassをコンパイルした場合、ネストされたルールセットをルートに書き出すことはできません。
.products {
.ttl {
color: #ff0000;
}
.contents {
margin-top: 20px;
}
}
コンパイル後のCSSは以下のようになります。
.products .ttl {
color: #ff0000;
}
.products .contents {
margin-top: 20px;
}
クラス名contentsをルートに書き出すには、@at-rootを利用します。
.products {
.ttl {
color: #ff0000;
}
@at-root .contents {
margin-top: 20px;
}
}
コンパイル後のCSSは以下のようになります。クラス名contentsのルールセットのみルートに書き出されました。
.products .ttl {
color: #ff0000;
}
.contents {
margin-top: 20px;
}
CSSアニメーションを実装する場合、@keyframesはルートに記述する必要があります。ただしSassで記述した場合、以下のようにクラス名ttlのanimationプロパティと@keyframesの位置が離れて関係性がわかりにくくなります。
.products {
.ttl {
color: #ff0000;
animation: show 0.2s linear 0s;
}
.contents {
margin-top: 20px;
}
}
@keyframes show{
from{
opacity: 0;
}
to{
opacity: 1;
}
}
そこで、animationプロパティの直後に@keyframesを記述して関係性を明確にします。@keyframesはネストされたルールセット内に記述するので、通常であれば以下のように@at-rootを利用します。
.products {
.ttl {
color: #ff0000;
animation: show 0.2s linear 0s;
@at-root @keyframes show{
from{
opacity: 0;
}
to{
opacity: 1;
}
}
}
.contents {
margin-top: 20px;
}
}
ただし@keyframesに限っては@at-rootを利用しなくてもルートに書き出されます。Sassのバージョン3.4からこの仕様になりました。
.products {
.ttl {
color: #ff0000;
animation: show 0.2s linear 0s;
@keyframes show{
from{
opacity: 0;
}
to{
opacity: 1;
}
}
}
.contents {
margin-top: 20px;
}
}
コンパイル後のCSSは以下のようになります。@keyframesはルートに書き出され、animationプロパティとの関係性も明確です。
.products .ttl {
color: #ff0000;
animation: show 0.2s linear 0s;
}
@keyframes show {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.products .contents {
margin-top: 20px;
}





