In this tutorial you’ll learn three ways to create easy angled edges using SVG. To begin with we’ll use an inline SVG, then we’ll use an SVG background on a pseudo-element, before finishing off with a Sass mixin. Let’s dive in!
Watch the Screencast
When I say “angled edges” I’m referring to things like the background on Stripe’s website:
Or the overlays on this website:
These would be easy enough to create using a graphics application; you could create the design, export as a single graphic, and load into your web page. However, if you want more flexibility, you should forget that approach. Let’s look at some alternative ways to get angled edges.
Quick Refresher in Hand-Coding SVG
Before we move on, if you need to remind yourself of the basics where hand-coding SVG is concerned, Kezz has you covered:
You’ll now see a large, black triangle in the bottom right of your page. Through our CSS we can style that triangle to suit our needs, filling it the same as our background so the hero appears to have been sliced at the bottom:
Now we’ll add a pseudo-element to our hero, to which we’ll add the SVG as a background image. First, we’ll need to encode our SVG so that we can actually use it in CSS. So grab the SVG code we wrote last time, change the points to 0,0 100,0 0,100 in order to flip it round, head over to URL-encoder for SVG, and paste the contents into the box:
Copy the Ready for CSS snippet and paste it into the pseudo-element styles:
Thanks to our Ziggy Stardust colors we can clearly see our SVG like this. Now we just need to color the triangle (using the fill='' attribute) so that it’s the same color as the purple at the bottom of the gradient:
The Importance of VW Units
There’s a reason we used vw units for the height of our SVG: we want the angle of our triangle to remain consistent no matter what the width of the viewport. If we were to use px units, the height of the triangle wouldn’t change for narrower screens, which would make the angle of the triangle more acute. Try it yourself!
3. The Sass Mixin
This final approach uses a Sass mixin to do all the heavy lifting, but it essentially achieves what we did in the previous example. Head over to the Angled Edges GitHub repo, grab the mixin, and include it in your project (I’m going to paste the whole thing into the SCSS window of a CodePen project).
Next, add our old friend the hero div to your markup. Add the basic styles too, so that we get the usual 300px gradient effect.
Then, within our .hero we add the mixin:
The parameters we need are as follows: we need our triangle to be outside the hero, at the bottom. The position of the point where the angle begins is lower right, the color we’re after is the purple #b06ab3, and then the height of the triangle will be 100. The limitation of this is that the mixin doesn’t accept relative values for the height or the width.