Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

sass - How do I access a specific element of a mapping?

I have the following mapping to contain all of the colours from my theme:

$_base-ocean:rgb(13,176,184);
$_base-hover:10%;

$themes: (
    ocean: (
        base: $_base-ocean,
        hover: darken($_base-ocean, $_base-hover)
    )
);

I know how to use an @each loop to get the key/value information from a mapping, but how can I directly access the value of a mapping without using a loop? I tried using square brackets like you would in other languages like JavaScript:

@each $name, $colors in $themes {
    [data-page="home"] {
        #slider-pagers{
            a.#{$name} {
                background-color: $colors[base]; // <- line 21
            }
        }
    }
}

But I get a syntax error instead:

 error sass/test.scss (Line 21: Invalid CSS after "...d-color: $color": expected ";", was "[base];")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have the use the map-get function. Sass does not provide a special syntax for accessing values of a mapping.

@each $name, $colors in $themes {
    [data-page="home"] {
        #slider-pagers{
            a.#{$name} {
                background-color: map-get($colors, base);
            }
        }
    }
}

Now you get the following output:

[data-page="home"] #slider-pagers a.ocean {
  background-color: #0db0b8;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...