loading...

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

stefanjudis profile image Stefan Judis Originally published at stefanjudis.com on ・2 min read

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 {
  /* 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 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 {
  /* 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 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.

CSS gradients using a 0 start value to remove redundant values

Posted on by:

stefanjudis profile

Stefan Judis

@stefanjudis

DevRel at Contentful. In love with web performance, new technologies, and accessibility – all the good stuff ✌️.

Discussion

pic
Editor guide