Welcome to this comprehensive guide on how to create and access Maps in SASS/SCSS. Our primary aim in this tutorial is to help you understand the concept of Maps in SASS/SCSS, how to create them, and how to access their data.
By the end of this tutorial, you will be able to:
- Understand what Maps are and their use cases in SASS/SCSS
- Create Maps in SASS/SCSS
- Access and manipulate data in Maps
SASS/SCSS Maps are like arrays, but they use key-value pairs instead of indexes. They are similar to JavaScript Objects or Python Dictionaries.
To create a map in SASS/SCSS, we use parentheses ()
and separate key-value pairs with a comma ,
. Each key-value pair is separated by a colon :
.
$color-map: (
primary: #007bff,
secondary: #6c757d,
success: #28a745,
danger: #dc3545,
);
To access data in a map, we use the map-get()
function. It takes two arguments - the map and the key.
body {
background-color: map-get($color-map, primary);
}
Let's take a look at a complete example:
// Defining a map
$theme-colors: (
"primary": #007bff,
"secondary": #6c757d,
"success": #28a745,
"danger": #dc3545
);
// Accessing data
body {
background-color: map-get($theme-colors, "primary"); // This will set the body's background color to #007bff
color: map-get($theme-colors, "secondary"); // This will set the body's text color to #6c757d
}
In this example, we defined a map named $theme-colors
with four key-value pairs. We then used the map-get()
function to access the values using their keys.
In this tutorial, we learned about SASS/SCSS maps - how to create them, and how to access their data. Maps are powerful tools that can help us write more efficient and manageable SCSS code.
To continue learning about SASS/SCSS, you can explore functions like map-has-key()
, map-keys()
, map-values()
, and map-remove()
, which provides more ways to manipulate maps.
$social-media-colors
with the following key-value pairs:Then, style a div
with the class .facebook
to have a background color of Facebook's color.
$font-sizes
with the following key-value pairs:Then, style three p
elements with classes .small
, .medium
, and .large
to have font sizes corresponding to the values in the map.
Solutions:
$social-media-colors: (
"facebook": #3b5998,
"twitter": #00acee,
"instagram": #C13584,
"linkedin": #0077b5
);
.facebook {
background-color: map-get($social-media-colors, "facebook");
}
$font-sizes: (
"small": 12px,
"medium": 16px,
"large": 24px
);
.small {
font-size: map-get($font-sizes, "small");
}
.medium {
font-size: map-get($font-sizes, "medium");
}
.large {
font-size: map-get($font-sizes, "large");
}
Happy coding!