1

What I want to do is like this

HTML

<div class="custom-color--ff0000">Red</div>
<div class="custom-color--00ff00">Green</div>
<div class="custom-color--0000ff">Blue</div>

CSS

.custom-color--(hex) {
  color:  '#' + (hex);
}

Is it possible to do this? Would I need Sass?

2 Answers 2

5

You can use a mixin to generate modifier classes in SASS:

@mixin add-color($argument) {
  $string: unquote($argument);

  &--#{$string} {
    color: unquote('#' + $argument);
  }
}

example:

.custom-color {
  @include add-color(404145);
  @include add-color(ff0000);
}

output in CSS:

.custom-color--404145 {
  color: #404145;
}

.custom-color--ff0000 {
  color: #ff0000;
}

Read more about it here: Generate All Your Utility Classes with Sass Maps

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

1 Comment

this doesn't allow you to dynamically change the color you still have to update your sass each time you want to use a different class to adjust the color. Is there a way to let sass just grab a part of a class name and use it to set the color ?
1

Don't know why you want to do this but I think you can achieve similar by using CSS custom properties.

For example:

HTML

<div class="custom-color" style="--red: #ff0000">Red</div>
<div class="custom-color" style="--green: #00ff00">Green</div>
<div class="custom-color" style="--blue: #0000ff">Blue</div>

CSS

.custom-color {
  color:  var(--red); // or what color you want
}

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.