Recently, Stephanie Eckles sent out a call to revive the use of CSS border-image. Not to use it with images — which requires a pretty nasty syntax — but to create Gradient Borders in CSS.

Curious to see what we can do with them, I whipped up a few demos using CodePen.

~

The most simple usage is to set some type of CSS gradient as the border-image:

div {
    border: 3em solid;
    border-image: linear-gradient(to right, green, yellow) 1;
}

See the Pen CSS Gradient Border by Bramus (@bramus) on CodePen.

~

To animate the border gradient you’ll need to add an angle in there — using a Custom Property — which you animate using some @keyframes.

div {
  --angle: 0deg;
  /* … */
  border-image: linear-gradient(var(--angle), green, yellow) 1;
  animation: 10s rotate linear infinite;
}

@keyframes rotate {
  to {
    --angle: 360deg;
  }
}

We could add individual keyframes for every 1 degree increase, or we can choose to have the browser properly interpolate this value automatically from 0deg to 360deg by registering it using the amazing @property

@property --angle {
  syntax: '<angle>';
  initial-value: 0deg;
  inherits: false;
}

⚠️ As @property is only supported in Chromium, the demos from here on down will only work in browsers based upon it. For browsers that don’t support it we could add individual keyframes for each step, but for demonstration purposes I’m skipping out on that here.

See the Pen CSS Gradient Border (Animated) by Bramus (@bramus) on CodePen.

~

While the effect here looks quite nice it won’t play nice with more than two colors. Take this rainbow animated gradient border for example:

See the Pen CSS Rainbow Gradient Border (Animated, Attempt 1) by Bramus (@bramus) on CodePen.

🕵️‍♂️ You can see best what’s going on by toggling the fill option there … ugh, that’s not what we want!

To fix that I first thought of using a radial gradient but what I need is a conic gradient:

This way each color of the gradient will extend nicely into the border, resulting in a correct animation.

div {
    /* … */
    border-image: conic-gradient(from var(--angle), red, yellow, lime, aqua, blue, magenta, red) 1;
}

💁‍♂️ To make the end of the gradient blend nicely into its begin color, we have to repeat the said color — e.g. red — as the last entry.

See the Pen CSS Rainbow Gradient Border (Animated) by Bramus (@bramus) on CodePen.

When toggling the fill you can see that border-image here stretches out the color perpendicular to its edge, instead of letting the gradient “pass”. This might not be 100% what you want, but for me it was exactly what I aimed for 🙂

~





Source link

Write A Comment