Maps in SASS

What is Maps in SASS and learn how to use in SASS

Maps in SASS / SCSS hold key-value pairs, and it enables users to lookup value with the help of key. Defining it is similar to defining a variable; it starts with $ following which we type the Map name. Within braces, we add key: value pairs. For example:

$font-weights: (

"regular": 400,

"light": 300,

"bold": 700

); 

This is a typical example that depicts Maps. In order to change the font weight of an element, we have defined font weights and within it, we have multiple key-value pairs which can be called in order to apply respective font weights to the text elements of the HTML. Kindly observe the syntax on declaring the variable and various key-value pairs which can be extended to any use cases for your project.

Try experimenting with font-family, define variables and add several key-value pairs for each text element such as paragraphs, heading 1, heading 2 and so on. Now that we have defined the maps, the next step is to call maps so that the respective CSS property applies to the text elements.

Calling Maps in your files

It’s easy to leverage SASS Maps by calling the map-get(variable, value) function. In place of the variable, we can add here font-weight and the corresponding value will automatically suggest based on the key-value name we define in the variable. 

body{

font-weight: map-get($font-weights, regular);

}

Equivalent CSS Code

body{

font-weight: 400;

}

In the next tutorial, we will be learning variables in SASS. You’ll learn how to create a variable in SASS/SCSS, how to use it for referencing, and the best practices while using variables in SASS.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *