Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

Today I read "While You Weren't Looking, CSS Gradients Got Better" by Ana Tudor. Ana's articles are always full of CSS knowledge, and I can only recommend following her and her work.

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

.element {
  /* some styles */
  background: linear-gradient(
    #fc6262 20%,     /* start at 0 and end at 20% */
    #50bbf6 20% 40%, /* start at 20% and end at 40% */
    #aaffef 40% 60%, /* start at 40% and end at 60% */
    #f9e699 60% 80%, /* and so on... */
    #2c3749 80%
  );
}

This approach works fine, but it has one downside. To define a hard border between two colors, you must specify an identical start and stop value. These duplicated values harm readability and maintenance.

A trick that caught my eye can help to avoid this duplication. You'll find a color-stop fixup section in the CSS images specification.

A color-what, you may ask? Let's have a look!

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 {
  /* some styles */
  background: linear-gradient(
    #fc6262 20%,   /* start at 0 and end at 20% */
    #50bbf6 0 40%, /* start at 20% (fixed because 0 is smaller than 20%) and end at 40% */
    #aaffef 0 60%, /* start at 40% (fixed because 0 is smaller than 40%) and end at 60% */
    #f9e699 0 80%, /* and so on... */
    #2c3749 0
  );
}

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

If you want to see some gradients using color-stop fixups, have a look at this example CodePen.

Gradient fixup video (mp4)

Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 12 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles