CSS 如何在 SASS mixin 中使用 !default?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10347651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 03:43:32  来源:igfitidea点击:

How to use !default in a SASS mixin?

csssasscompass-sass

提问by Wabbitseason

I have this SASS mixin:

我有这个 SASS mixin:

@mixin micro-clearfix
    &:after,
    &:before
        content: ""
        display: table
    &:after
        clear: both
    * html &
        height: 1% !default
    *+html &
        min-height: 1% !default

Unfortunately, it does not compile, unless I remove !defaultwhich would be the point of having this mixin.

不幸的是,它无法编译,除非我删除!default了使用此 mixin 的重点。

The error message I'm getting is:

我收到的错误消息是:

Invalid CSS after "1% ": expected expression (e.g. 1px, bold), was "!default")

What I'd like to achieve is that if height(or min-height) has already been defined for the selector then the mixin should use that value, otherwise it should define this property as 1%.

我想要实现的是,如果height(或min-height) 已经为选择器定义,那么 mixin 应该使用该值,否则它应该将此属性定义为 1%。

I don't wish to use zoomsince that's not a valid property and I like to keep my CSS clean.

我不想使用,zoom因为这不是一个有效的属性,我喜欢保持我的 CSS 干净。

Am I using !defaultthe wrong way?

我是不是用!default错了方法?

I have Compass 0.12.1 and SASS 3.1.10.

我有指南针 0.12.1 和 SASS 3.1.10。

采纳答案by Wabbitseason

Here's how I've done it finally:

这是我最终完成的方法:

@mixin micro-clearfix
    $minHeight: 1% !default
    &:after,
    &:before
        content: ""
        display: table
    &:after
        clear: both
    * html &
        height: $minHeight
    *+html &
        min-height: $minHeight

回答by Waiting for Dev...

!defaultis intended to use only when declaring variables: http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#variable_defaults_

!default仅在声明变量时使用:http: //sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#variable_defaults_

What you are trying to do should be done with CSS !importantdeclaration, which should be used in the rule outside the mixin (the one you want to prevail). Anyway, using !importantusually it's not a good practice. Maybe you could rely on cascade or specificity.

你想要做的应该用CSS!important声明来完成,它应该用在 mixin 之外的规则中(你想要占上风的那个)。无论如何,!important通常使用这不是一个好习惯。也许您可以依靠级联或特异性。