2

Sassで次のCSS出力を達成しようとしています:

.selector1 + .selector1, .selector2 + .selector2 {
    margin-top: -80px;
}

@extend 機能がその仕事をするはずです:

%sibling-selector {
    & + & {
        margin-top: -80px;  
    }
}
.selector1 {
    @extend %sibling-selector;
}
.selector2 {
    @extend %sibling-selector;
}

しかし、extend 関数は、extend only クラス定義 (%sibling-selector) の 2 つの親参照 (&) に問題があるようです。これは出力です:

.selector1 + .selector1, .selector2 + .selector1, 
.selector1 + .selector2, .selector2 + .selector2 {
    margin-top: -80px;
}

したがって、@extend 関数は、@extend 定義を使用するセレクターの組み合わせごとに兄弟セレクターを作成しています。

@extend は現在のセレクターの「スコープ」にとどまると予想されるため、アンパサンドは現在のセレクターに置き換えられます。これはバグですか、それとも機能ですか? :-)

この仕事に mixin を使用できることはわかっていますが、

@mixin sibling-selector {
    & + & {
        margin-top: -80px;
    }
}
.selector1 {
    @include sibling-selector;
}
.selector2 {
    @include sibling-selector;
}

しかし、それは重複した CSS 定義を作成します:

.selector1 + .selector1 {
    margin-top: -80px;
}
.selector2 + .selector2 {
    margin-top: -80px;
}

Sassでそれを正しくする方法はありますか?

4

1 に答える 1

1

@extend望ましい結果を得る方法ではないようです: https://github.com/nex3/sass/issues/848#issuecomment-20903684

そこで、兄弟セレクターの作成を「自動化」するために、小さな@eachループを使用してセレクターのリストを作成しました。

$siblingSelectors: ();
@each $selector in selector1 selector2 selector3 {
    $classSelector: unquote('.prefix-' + $selector);
    $siblingSelectors: append($siblingSelectors, unquote($classSelector + ' + ' + $classSelector), comma);
}

#{$siblingSelectors} {
    margin-top: 80px;
    &.large {
        margin-top: -100px;
    }
}

次の結果が得られます。

.prefix-selector1 + .prefix-selector1, .prefix-selector2 + .prefix-selector2 {
    margin-top: -80px;
}
.prefix-selector1 + .prefix-selector1.large, .prefix-selector2 + .prefix-selector2.large {
    margin-top: -100px;
}
于 2013-07-15T08:19:22.177 に答える