Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I create CSS gradients the "right way"?

This question stems from this minutephysics video I watched a while back: Computer Color is Broken

It describes how the correct way to blend colors is to use the square root of the average of the squares of the R, G and B values, rather than simply taking the average.

So I was curious and decided to test how CSS implements gradients with a simple Red – Green gradient:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

div {
    width: 600px;
    height: 600px;
    background: linear-gradient(to right, rgb(0,255,0), rgb(255,0,0));
}
<div></div>

image showing default css gradient

As you can see, the gradient is kind of ugly, with dark yellow in the middle.

I decided to implement the correct gradient using gradient stops that follow the sqrt curve, and the result is definitely better:

div {
    width: 600px;
    height: 600px;
    background: linear-gradient(to right, 
        rgb(000,255,000),
        rgb(127,221,000) 25%,
        rgb(180,180,000) 50%,
        rgb(221,127,000) 75%,
        rgb(255,000,000) 100%
    );
}
<div></div>

image showing modified css gradient

Due to the limited number of stops, the resulting render is a bit blocky, but the overall gradient does look noticeably better than the default. Adding even more stops does improve it even more:

div {
    width: 600px;
    height: 600px;
    background: linear-gradient(to right, 
        rgb(000,255,000),
        rgb(090,239,000) 12.5%,
        rgb(127,221,000) 25%,
        rgb(156,201,000) 37.5%,
        rgb(180,180,000) 50%,
        rgb(201,156,000) 62.5%,
        rgb(221,127,000) 75%,
        rgb(239,090,000) 87.5%,
        rgb(255,000,000) 100%
    );
}
<div></div>

enter image description here

My question is, is there a way to achieve a more continuous gradient like this in CSS (either vanilla or by using some other tool)?

>Solution :

Using a polar colourspace with interpolation can give better results.

div {
    width: 600px;
    height: 600px;
    background: linear-gradient(
      to right in oklch shorter hue,
      rgb(0,255,0),
      rgb(255,0,0)
    );
}
<div></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading