"Hard CSS gradients" can be shortened to not include redundant values

This post is part of my Today I learned series in which I share all my learnings regarding web development.

Today I was reading While You Weren't Looking, CSS Gradients Got Better by Ana Tudor. Ana's articles are always full of CSS knowledge, and I can't recommend enough to follow her and her writing.

This article includes a nifty little CSS gradient trick I didn't know. Let's say you have a linear-gradient that includes "hard color stops". Then your CSS looks like the following:

.element { background : linear-gradient ( #fc6262 20% , #50bbf6 20% 40% , #aaffef 40% 60% , #f9e699 60% 80% , #2c3749 80% ) ; }

This works fine, but it has one downside. To define a hard border between two colors you have to define an identical start and stop value. This leads to duplicated values and harms readability and maintanaince.

The gradient detail that caught my eye can help to avoid this duplication. If you head over to the CSS images specification, you'll find a color-stop fixup section.

If a color stop or transition hint has a position that is less than the specified position of any color stop or transition hint before it in the list, set its position to be equal to the largest specified position of any color stop or transition hint before it.

The above fixup rule defines that if a color-start value is smaller than the previous stop value, the stop value will be used as a start. This behavior allows the usage of a little trick. CSS gradients, including hard color stops, can be adjusted and use 0 as start values. Redundant color-start values can be removed.

.element { background : linear-gradient ( #fc6262 20% , #50bbf6 0 40% , #aaffef 0 60% , #f9e699 0 80% , #2c3749 0 ) ; }

Ben Briggs also shared that cssnano uses this technique to minify CSS. Pretty cool! 😲

If you want to see some gradient, you can have a look at this example CodePen.

Side note: The CodePen examples includes a linear and conical gradient. At the time of writing, only Chromium browsers and Safari support conical gradients.