css - 发送属性作为 mixin 的参数

标签 css less media-queries less-mixins

我想分解所有媒体查询并将 CSS 属性作为参数传递。

.bp1(@css){
    @media (max-width: 959px){
        @css
    }
}

.bp1(width: 186px;);

不幸的是,这不会起作用,并且会使 Less 失败:(

最佳答案

从Less v1.7.0开始,可以通过detached rulesets as parameter to a mixin .

Quoting Less Website:

Detached ruleset is a group of CSS properties, nested rulesets, media declarations or anything else stored in a variable. You can include it into a ruleset or another structure and all its properties are going to be copied there. You can also use it as a mixin argument and pass it around as any other variable.

请注意,构成规则集一部分的属性必须包含在 {} 内。此外,在分离规则集调用之后必须使用括号 (())(如 @css();)。如果末尾没有括号,调用将无法工作。

.bp1(@css){
    @media (max-width: 959px){
        div{
            @css(); // detached ruleset call
        }
    }
}

.bp1({width: 186px;}); // passing ruleset to mixin

编译输出:

@media (max-width: 959px) {
    div {
        width: 186px;
    }
}

或者,可以将规则集分配给一个变量,该变量又可以在 mixin 调用中传递,如下所示。编译时这也会产生相同的输出。

.bp1(@css){
    @media (max-width: 959px){
        div{
            @css(); // detached ruleset call
        }
    }
}

@ruleset: {width: 186px;};
.bp1(@ruleset);

使用此功能,不仅可以传递属性组,还可以传递选择器(如下所示):

.bp1(@css){
    @media (max-width: 959px){
        @css(); // detached ruleset call
    }
}
    
.bp1({
    div{width: 186px;}
    div#header{color: gold;}
});

编译输出:

@media (max-width: 959px) {
    div {
        width: 186px;
    }
    div#header {
        color: gold;
    }
}

关于css - 发送属性作为 mixin 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12132738/

相关文章:

javascript - 在 Github 页面上使用 Slick 更改箭头的颜色

css less mixin rem 计算器而不被定向到字体或其他东西

css - LESS - 将 mixin 分配给变量并重用

html - 按分辨率显示/隐藏不同数量的元素

html - 如何更改仅通过使用 CSS 和媒体查询动态生成的图像的 url?

javascript - 我可以使用 ASP.NET WebForms 母版页在每个内容页中包含不同的 javascript/css 文件吗?

html - 如何删除 Bootstrap div 之间的空间

css - 如何显示与其他元素颜色不同的面包屑元素

angular - 使用 Webpack 将外部 less 文件导入到 app.component.less 文件中

html - Nexus 7 screen.width 返回 800 但媒体查询最大宽度 : 720px still applies