The Clank Blog

CSS Gradient Strokes

Posted on June 06, 2013 by Wolfr

If you look closely at iOS buttons, you’ll see that they actually have a gradient running in their strokes:

There is no CSS gradient stroke feature in CSS. Fortunately, we can fake it with pseudo elements.

In the first version of Clank, I had extra elements around my buttons to make it work properly:

  <a class="btn"><span><span>Hello</span></span></a>

This is problematic for framework adoption since it’s another thing people will have to learn.

This pretty messy code since changed to:

  <a class="cl-btn">Hello</a>

I did manage the gradient strokes by hooking them to the :before and :after elements. E.g. let’s say you have a button with a green to dark green gradient background:

.cl-btn {
  background: linear-gradient(to bottom, green 0%, darkgreen 100%); /* W3C */
}

If we include two pseudo elements that contains 100% of the space of the original element, we can use these to fake our new background:

.cl-btn:before,
.cl-btn:after {
  position: absolute;
  content: "";
  width: 100%;
  height: 100%;
  min-width: 100%;
  white-space: nowrap;
}

By using a negative z-index we can order the :before and :after elements:

.cl-btn:after {
  top: -1px;
  left: -1px;
  padding: 1px; /* This makes for 1px gradient border */
  z-index: -2;
}

.cl-btn:before {
  top: 0;
  left: 0;
  padding: 0;
  z-index: -1;
}

Because we used negative z-index, create a new stacking context on .cl-btn so the elements don’t go below the original “page”.

.cl-btn {
    // Create new stacking context for :before and :after
    z-index: 1;
}

Now if we apply our backgrounds to the new pseudo elements, we have gradient borders without extra markup:

.cl-btn:before {
    background: linear-gradient(to bottom, green 0%, darkgreen 100%); /* W3C */
}

.cl-btn:after {
    background: linear-gradient(to bottom, darkgreen 0%, reallydarkgreen 100%); /* W3C */
}

Now, the reality is a bit more complicated.

A simple implementation without z-indexing can be found here (demo).

If you’re feeling brave, poke around in the SCSS source for Clank here.

comments powered by Disqus