Chris Straw

Customizing Bootstrap Themes with Sass’s map-merge()

In the ever-evolving world of web design, styling tools play a pivotal role in helping designers and developers achieve their vision. Among these tools, Sass (Syntactically Awesome Style Sheets) stands out as a potent CSS preprocessor, offering capabilities beyond standard CSS.

Today, we’ll dive into one of Sass’s handy features: the map-merge() function, a lifesaver when working with maps in Sass.

What are Maps in Sass?
In Sass, a map is like an associative array or a dictionary in other programming languages. It holds key-value pairs, and these keys can be any Sass data type, like numbers, strings, or colors. Here’s a quick example:

$colors: (
  primary: #3498db,
  secondary: #e74c3c,
  accent: #f39c12

Introducing map-merge()

Imagine you have default settings in a map and want to overwrite specific values based on user input or other conditions. Instead of rewriting the entire map or creating multiple conditional statements, you can use the map-merge() function. It merges two maps together, with the second map’s values taking precedence if keys overlap.

Let’s explore this with an example:

$default-colors: (color1: red, color2: blue);
$user-colors: (color2: green, color3: yellow);

$merged-colors: map-merge($default-colors, $user-colors);

Result of $merged-colors:

As you can see, color2 from $default-colors was overwritten by the color2 from $user-colors.

Customizing Bootstrap’s Theme Colors

Bootstrap defines a set of default theme colors in a map:

$theme-colors: (
  primary: #007bff,
  secondary: #6c757d,
  success: #28a745,
  info: #17a2b8,
  warning: #ffc107,
  danger: #dc3545,
  light: #f8f9fa,
  dark: #343a40

Now, let’s say you want to change the primary and danger colors for a specific project without altering the other theme colors. You can create a new map:

$custom-colors: (
  primary: #3498db,
  danger: #e74c3c

With map-merge(), you can merge these two maps:

$theme-colors: map-merge($theme-colors, $custom-colors);

Now, your $theme-colors map has been updated with the new values, and you can use it throughout your Bootstrap theme.