【问题标题】:Mixin using "&" selector without changing HTML classMixin 使用“&”选择器而不更改 HTML 类
【发布时间】:2018-06-01 22:44:37
【问题描述】:

我想问一个关于mixin uage的问题

我的目标是使用 mixin 根据不同的语言更改 TESTING 的字体大小。必须在 HTML 标签中设置 Home 类和语言类。

<html class='Home en'>
    <body>
        <div class='text'>TESTING</div>
    </body>
</html>

CSS 设置

.Home {
    .text {
        @include font(20)
    }
}

我写了一个mixin来根据不同的语言处理字体大小

@mixin font($size) {
    font-size: $size + px;

    .en & {
        font-size: $size - 5 + px;
    }
}

但是,输出将变为: .en .Home .text { ... } 而不是 .en.Home .text { ... }

如何使用 mixin 处理这种情况?或者我可以使用任何其他替代方法来解决此问题而不更改 HTML 标签中的类?

谢谢大家!

【问题讨论】:

    标签: html sass mixins


    【解决方案1】:

    您需要解析&amp; 引用并使用第一个选择器与.en 连接,然后获取选择器的其余部分来构建完整的选择器。 &amp; 是一个包含所有父选择器的列表列表,因此您可以使用 Sass 列表函数遍历该列表。

    尝试以下方法:

    @mixin font($size) {
        font-size: $size + px;
    
        // Get the first parent selector, to aply the '.en'
        $root: nth(nth(&, 1), 1);
    
        // Get all the other parent selectors
        $rest : ();
        @for $i from 2 through length(nth(&, 1)) {
            $rest: append($rest, nth(nth(&, 1), $i));
        }
    
        // Create the selector
        $selector: unquote(".en#{$root} #{$rest}");
    
        // Print it at root
        @at-root #{$selector} {
            font-size: $size - 5 + px;
        }
    }
    

    查看工作代码here

    【讨论】:

    • 这不适合我。
    • 太棒了!如果它解决了您的问题,请将其设置为有效答案! ;-)
    猜你喜欢
    • 1970-01-01
    • 2014-01-19
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多