1

In CSS, linear gradient css looks like:

   background-image: linear-gradient(blue, lightblue);

This starts the gradient at blue, and ends at lightblue. Not actually pretty, but it serves as an example.

Now, what if you only have the start color? What if you start with a passed parameter for color (imagine it's passed in an MVC ViewModel)? For example, you may have been passed a value of 'red', and you would like to have a linear gradient from that starting 'red' to some subtly lighter color of red to make a nice gradient?

Would you need to know, or convert, 'red' into hex values, and then generate the gradient stop color by manipulation of the hex number? Is there a 'normal' way to do this? Ie

  1. some trick to convert 'red' to a hex value like #A11634
  2. some trick to apply some math to 'make A11634 a subtly lighter color'?

OR

  1. some gradient trick to automagically create a gradient with one color, to a lighter version of that color?

1 Answer 1

5

Here's a very simple solution to save you the hassles of manipulating the colours; instead of passing the named colour to the gradient, set it as the background-colour of your element with a white gradient as the background-image, fading from completely transparent to however much you want to lighten your base colour by.

Here's an example using the background shorthand property with the colour transitioning from bottom to top:

div{
    background-image:linear-gradient(0deg,rgba(255,255,255,0),rgba(255,255,255,.75));
    height:100px;
    margin:0 0 10px;
}
#red{
  background-color:red;
}
#green{
  background-color:green;
}
<div id="red"></div>
<div id="green"></div>

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

12 Comments

I don't see any gradient...?? I'm using Chrome
Perhaps: background-color: red; background-image: linear-gradient(to bottom, white -5%, rgba(255,0,0,0));
What browser are you using? If you're using an older one, you may need to prefix the gradient. See caniuse.com/#feat=css-gradients I'll increase the alpha of the white at the end to make it more apparent, just in case that's the issue.
I have changed your gradient to make it more visible. And also split the background in individual properties; I believe it is easier to use this way. Good answer, by the way.
Thanks, @vals, you beat me to it :)
|

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.