We talk about CSS ribbons in web design when a strip of box (called ribbon) wraps another box. It’s a fairly used design technique to decorate text, especially headings. On W3C‘s website you can check out how properly used CSS ribbons can help structure content in a subtle way.
In this post, we’re going to look at how we can create a angled edge effect (horizontally) on…Read more
So, in this post we’re going to see how to create a simple CSS ribbon that you can use to enhance the headings on your website. Thanks to CSS transformations, we can create this design with a much simpler code base than before.
First, we create a <header> HTML element to which we’ll later add the ribbon design. We place it inside a <section> tag we mark with the .card selector that represents a rectangle box the ribbon will wrap around.
We’ll use a CSS variable (allows us to store and reuse a CSS value) called --p to store the padding value. The value of the padding property uses the var(--p) syntax for the left and right paddings of the ribbon so that it can be easily widened. The --p variable later will be reused multiple times; that makes our code flexible.
Cascading Style Sheet (CSS) is primarily intended for applying styles to the HTML markup, however in some cases…Read more
Both pseudo-elements inherit the background color of .ribbon, and we use the filter: brightness(.5) rule to darken their color a bit. They are also absolutely positioned within their (relatively positioned) parent.
Their width needs to be the same as the padding size, and we place them to the left and right ends of the ribbon using the left: 0 and right: 0 style rules.
As you can see the edges of the sides don’t align after the transformation, so we need to pull them down.
Align the sides
To determine the proper length by which we need to move the sides down, we turn to trigonometry. What we need to find is x, as y is the width of the sides (equals to the padding size of .ribbon), and the angle θ is 45° (the angle of the skew).
The resulting x then needs to be halved, as there are a left and a right side as well.
If you’re using any CSS preprocessor check if it has a tan function, otherwise refer to a tangent chart or a calculator to find out the tangent value of the angle. We’re lucky as tan 45° is 1, which means that the value of x equals to y in our case.