Soroush Mirzaei Soroush Mirzaei - 6 months ago 6
CSS Question

Getting the default state color (currentColor) in a different state such as hovered

Is there a keyword like

currentcolor
which allows us to get the color of a class in its default state?

For example, I'm trying to create a re-useable button style, and
currentcolor
keyword helps a lot until I try to create the
:hovered
state.

.outline-btn {
background-color: transparent;
border: 1px solid currentColor;
padding: 0.5em 1.5em;
}

.rounded-btn {
border-radius: 50px;
}


The default state looks the way we want and changing the
color
or the
font-size
would also adjust the rest of the properties.

button

But we want the
:hovered
state to invert the colors (white text and orange background in this case)

.outline-btn:hover, .outline-btn:active, .outline-btn:focus {
background-color: currentcolor;
color: white;
}


But since in this state the
color
becomes white, everything else also turns white.

Is there a way that we can achieve the behavior that we want without having to create multiple classes for the different button styles that we want?

Desired effect on hover:

button on hover

Also I forgot to mention that I am using
SCSS
if that helps.

Thanks for your time :)

Answer

If you think about it, you're essentially wanting currentColor to act as a variable -- to hold a constant value. The upcoming CSS variables will help with this, but until they're better supported, we have Sass variables.

By defining the colors as variables you can write them out very verbosely and specifically, but only have to change the color in one place when needed.

$btn-color: red;
$btn-bg: transparent;

.outline-btn {
  background-color: $btn-bg;
  border: 1px solid $btn-color;
  padding: 0.5em 1.5em;
  color: $btn-outline-color;

  &:hover,
  &:active,
  &:focus {
    background-color: $btn-outline-color;
    color: $btn-outline-bg;
  }
}

You could go a step further and have those variables set to equal previously set variables you're using for the body/html color background, e.g., $bg-bg: $body-bg; $btn-color: $text-color;. I love currentColor as well and this isn't as clean as that, but it might be more appropriate in this case.

You can then build this out as a mixin as user6292372 noted. Something like:

@mixin buttonBuilder($color, $bg) {
  background-color: $bg;
  border: 1px solid $color;
  color: $color;

  &:hover {
    background-color: $color;
    color: $bg;  
  }
}

...

.outline-btn {
  @include button-builder($btn-color, $btn-bg);
}

Then you can easily make multiple variants.

Comments