【问题标题】:Is there a way for implementing this in sass?有没有办法在 sass 中实现这一点?
【发布时间】:2020-03-19 07:10:21
【问题描述】:

我找不到在 sass 中实现所需内容的方法,您可以帮助我了解这一点。

假设这是代码。

p, span {
    font-size: 12px;
    // other styles

    &:hover {
        color: blue;
    }
}

我需要的是一种为这两个选择器中的每一个添加不同颜色的悬停颜色的方法,假设 p 元素为蓝色,跨度为红色,目前我是这样做的:

p, span {
    font-size: 12px;
    // other styles
}

p:hover {
    color: blue;
}

span:hover {
    color: red;
}

这里的问题是选择器的重复,这似乎不是一个好习惯,我正在考虑这样的事情或任何类似的方式:

p, span {
    font-size: 12px;
    // other styles

    &:first-selector:hover {
        color: blue;
    }
    &:second-selector:hover {
        color: red;
    }
}

提前致谢。

【问题讨论】:

    标签: sass css-selectors dry


    【解决方案1】:

    您的想法的问题是,在&:nth-selector:... 中,您要么重复选择器(导致您当前的操作方式没有任何改进),要么引入一些幻数,在我看来这会降低可读性相当大。

    你可以做的是扩展一个基本的p、span、style:

    %p_span_placeholder_selector {
        font-size: 12 px;
        // other styles
    }
    
    p {
        @extends %p_span_placeholder_selector;
        &:hover {
            color: blue;
        }
    }
    
    span {
        @extends %p_span_placeholder_selector;
        &:hover {
            color: red;
        }
    }
    

    您可以阅读更多关于 @extend in the docs 的信息。 使用 mixin 可以实现类似的结果:

    @mixin p_span_mixin {
        font-size: 12 px;
        // other styles
    }
    
    p {
        @include p_span_mixin;
        &:hover {
            color: blue;
        }
    }
    
    span {
        @include p_span_mixin;
        &:hover {
            color: red;
        }
    }
    

    推荐阅读更多关于这两种方法的(缺点)优点和适用性的信息:https://webinista.com/updates/dont-use-extend-sass/

    【讨论】:

    • 嘿@BernhardWebstudio,感谢您的方法,我喜欢“@extend”的想法。
    猜你喜欢
    • 1970-01-01
    • 2011-10-04
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多