This Sass code creates a map of settings, gets and checks keys, adds a new key, and uses the values in CSS styles. It also shows how to get all keys and values.
SASS
@use'sass:map';
$settings: (
font-size: 1.2rem,
color: #0055cc,
margin: 1rem
);
// Get font size
$font-size: map.get($settings, font-size);
// Check if padding exists
$has-padding: map.has-key($settings, padding);
// Add padding
$new-settings: map.merge($settings, (padding: 2rem));
// Get all keys
$keys: map.keys($new-settings);
// Get all values
$values: map.values($new-settings);
body {
font-size: $font-size;
color: map.get($new-settings, color);
margin: map.get($new-settings, margin);
padding: map.get($new-settings, padding);
}
/* Keys: #{$keys} *//* Values: #{$values} */
OutputSuccess
Important Notes
Maps in Sass are like labeled boxes where you keep pairs of names and values.
Use map.get to find a value by its name.
Always check if a key exists with map.has-key before using it to avoid errors.
Summary
Built-in map functions help manage key-value pairs in Sass easily.
You can get, check, add, and list keys and values with simple functions.
Using maps keeps your styles organized and flexible.
Practice
(1/5)
1. Which Sass built-in map function is used to check if a key exists in a map? map-get(), map-has-key(), map-keys(), or map-values()?
easy
A. map-has-key()
B. map-get()
C. map-keys()
D. map-values()
Solution
Step 1: Understand the purpose of each function
map-get() retrieves a value, map-keys() lists keys, map-values() lists values, and map-has-key() checks if a key exists.
Step 2: Identify the function that checks key existence
The function map-has-key() returns true or false if a key is in the map.
Final Answer:
map-has-key() -> Option A
Quick Check:
Check key presence = map-has-key() [OK]
Hint: To check keys, use map-has-key() [OK]
Common Mistakes:
Confusing map-get() with map-has-key()
Using map-keys() to check key existence
Thinking map-values() checks keys
2. Which of the following is the correct syntax to get the value for key "color" from a Sass map named $theme?
easy
A. map-get($theme, color)
B. map-get(color, $theme)
C. map-get($theme, $color)
D. map-get($theme, "color")
Solution
Step 1: Recall map-get() syntax
The correct syntax is map-get($map, $key) where the key is a string or identifier.
Step 2: Identify correct key format
Keys that are strings must be quoted with double or single quotes. Here, "color" is correct.
Final Answer:
map-get($theme, "color") -> Option D
Quick Check:
Correct syntax uses map-get($map, "key") [OK]
Hint: Use quotes around string keys in map-get() [OK]
Common Mistakes:
Omitting quotes around string keys
Swapping map and key order
Using a variable ($color) instead of a quoted string key