9

Assume I have something like this:

.object {
  $primary-color: blue;
  h1 {
    font-size: 40px;
    color: $primary-color; 
  }
  p {
    font-size: 20px;
    color: $primary-color; 
  }
}

Now I'll be having a blue object. But let's say I want to make the same object but in a red color, it might be intuitive to write

.object red {
  $primary-color: red;
}

and expect all the $primary-color to change to red, but this is not valid in SCSS. What I have to write is:

.object red {
  $primary-color: red;
  h1 { color: $primary-color; }
  p { color: $primary-color; }
}

If I do it this way, I can still keep the 40px font size in h1 and 20px in p and will change all colors to red. However, once my code gets bigger, this will become harder and harder to maintain.

Does SCSS provide any tool to make this task more modular and maintainable?

2 Answers 2

9

For sure SCSS provide such function but you can also do it with CSS using CSS variables:

.object h1 {
  font-size: 40px;
  color: var(--p, blue);
}

.object p {
  font-size: 20px;
  color: var(--p, blue);
}
.red {
  --p:red;
}
.other-color {
  --p:rgb(15,185,120);
}
<div class="object">
<h1>Blue title</h1>
<p>blue text</p>
</div>
<div class="object red">
<h1>red title</h1>
<p>red text</p>
</div>
<div class="object other-color">
<h1>red title</h1>
<p>red text</p>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Holy crap, I didn't even know this is possible in CSS! I actually found out that I should use @each in SCSS to achieve this, but there's no reason to use that anymore :). Thanks man.
3
//you can use sass maps - if you want do add new color version of component just add the color to variables to the map.


  //define colors

$product-color-red: red;
$product-color-blue: blue;

//define color map
$colors-list: (
  primary : $product-color-red,
  secondary : $product-color-blue
);

// generate componenent with multiple colors
@each $key in map-keys($colors-list) {
  .mycomponent {
    &.color-#{$key} {
      p {
        color: map-get($colors-list, $key);
      }
    }
  }
}

//effect below, you could change color-xxx class to component variant name
.mycomponent.color-primary p {
  color: red;
}

.mycomponent.color-secondary p {
  color: blue;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.