首页 > 解决方案 > 从源映射键创建类名

问题描述

我收到一条错误消息,说 ('background-color': #333) 不是有效的 css。我正在尝试将主题名称附加到 .body-- 对于每个主题(目前只有一个)。在我看来,该错误正在尝试将主题名称的内容添加到 .body-- 而不仅仅是它的标题。

$themes: (
    'dark': (
        'background-color': #333
    ),
);

@each $theme-name in $themes {
    .body--#{$theme-name} {
        & .container {
            background-color: map-get($theme-name, background-color);
        }
    }
}

我试图得到:

.body--dark {}
.body--dark .container {background-color: #333}

谢谢

标签: sass

解决方案


问题出在你的@each陈述中。您得到的只是地图值,而不是键值。

$themes: (
    'dark': (
        'background-color': #333
    ),
);

// get the key and the value in two separate variables: first variable is the key, second one the value
@each $theme-name, $theme-config in $themes {
    .body--#{$theme-name} {
        .container {
            background-color: map-get($theme-config, 'background-color');
        }
    }
}

请注意,您不需要&for 嵌套选择器。这只是默认行为。仅用于&伪类、连接类名、聚合类名和其他一些奇怪的选择器用法。检查我对this note on this other question的回答。


推荐阅读