7

I am creating a Button component using styled-system (with styled-components).

I want to create a hover effect that slightly lightens the color of the button, regardless of what that color is.

For instance, let's imagine three buttons -- a default button, primary button and secondary button:

<Button>Default</Button>
<Button bg="primary">Primary</Button>
<Button bg="secondary">Secondary</Button>

And let's imagine that the default color is dark grey, the primary color is green and the secondary color is blue.

So, if I hover over the default button, the color should be a slightly lighter form of the dark grey. For the primary, a slightly lighter green, for secondary, a lighter blue.

I cannot figure out, though, how to do this?

Any ideas?

Moshe
  • 6,011
  • 16
  • 60
  • 112
  • 1
    Possible duplicate of [CSS: lighten an element on hover](https://stackoverflow.com/questions/16178382/css-lighten-an-element-on-hover) – ControlAltDel May 23 '19 at 16:33

2 Answers2

11

The recommended way is to use styled-system's buttonStyle variant.

This requires adding the buttonStyle system prop, then providing a buttons scale on the theme object. Note that variants are raw CSS object defs, not system props.

Button.js

import styled from "styled-components"
import { buttonStyle } from "@styled-system/variant"

export default styled('button')({}, buttonStyle)

theme.js

export default {
  buttons: {
    primary: {
      backgroundColor: "red",
      '&:hover': {
        backgroundColor: "pink" // use polished `lighten`, etc
      }
    }
  }
}

Usage: Just specify the variant.

<Button variant="primary">Primary Button</Button>

Here's the CodeSandbox demo: https://codesandbox.io/s/zealous-noether-lxjeu?fontsize=14

Aaron Noel De Leon
  • 1,139
  • 10
  • 9
-2

You'll need to use some css classes.

you can use filter: brightness(150%) or custom lighten colors. But if you use a css pre processor like SASS or Less you have pre-built functions.

For example:

button {
  background: red;
  color: white;
}

.primary {
  background: green;
}

.secondary {
  background: blue;
}

button:hover {
  filter: brightness(150%);
}
<Button>Default</Button>
<Button class="primary">Primary</Button>
<Button class="secondary">Secondary</Button>
l-portet
  • 636
  • 7
  • 14
  • Thanks for your suggestion. However, like with opacity, I'm not crazy about how brightness looks. – Moshe May 23 '19 at 19:00
  • Yep, I understand, but if you want to stay on CSS I don't see how you can do it automatically. This is why I talked about SASS/Less and others preprocessors. With them, you just use `background: lighten($color, 50%)` for example. – l-portet May 23 '19 at 19:05
  • I'm using Styled-Components with the polished library. The problem is that someone can modify the background color using a prop -- thus overriding the value of the `$color` variable. With that said, I think this answer will do the trick: https://stackoverflow.com/a/26073962/7477670 – Moshe May 23 '19 at 19:12