CSS only zigzag patterns explained

Using CSS to create more complex backgrounds without the need for images

Week 142 was posted by Charanjit Chana on 2020-07-13.

This is the first in a series of articles where I'll look at creating CSS patterns work and explain how it's achieved. First up is the zig-zag pattern, this is what we'll be creating:

Using CSS' linear-gradient function to create triangles you can build up the pattern bit by bit. Let's break the pattern down so we can see the triangles we need to create:

Each part of the pattern is split into 4 squares and there are two triangles in each. Each of these squares is mirrored and repeated to create the zigzag. So we need to create 4 patterns that are repeated. Let's create the first one:

background: linear-gradient(-135deg, teal 25%, transparent 25%) -50px 0;

This creates a diagonal pattern that is teal 25% of the way down, then transparent for the remainder. It's also been rotated and set to be offset vertically by -50px. Next, we'll create a mirror of this pattern that gives us the top two squares of the pattern.

background: linear-gradient(135deg, teal 25%, transparent 25%) -50px 0,
linear-gradient(-135deg, teal 25%, transparent 25%) -50px 0;

You can set multiple linear gradients, just comma separate the definitions. This is exactly the same as the previous triangle, just rotated in the opposite direction. So now we're defining two linear gradients that go in two different directions and when they repeat we end up with row after row of larger downward facing triangles.

background: linear-gradient(135deg, teal 25%, transparent 25%) -50px 0,
linear-gradient(-135deg, teal 25%, transparent 25%) -50px 0,
linear-gradient(45deg, teal 25%, transparent 25%);

In the rows between the downward facing arrow we now have our third triangle. This doesn't require any positioning, just rotating. So now we need to be mirror this triangle too to give us the complete pattern and we can do that by redefining the gradient from the last step, but rotating it in the opposite direction:

.zigzag {
background: linear-gradient(135deg, teal 25%, transparent 25%) -50px 0,
linear-gradient(-135deg, teal 25%, transparent 25%) -50px 0,
linear-gradient(45deg, teal 25%, transparent 25%),
linear-gradient(-45deg, teal 25%, transparent 25%);
background-size: 100px 100px;
}

This is the code you'll need to recreate the pattern. To make the pattern larger, change the -positioning of the first two linear-gradients to half of whatever you choose as the background-size and you now have a repeatable pattern created with just CSS!

And go wild with the colours, try to fit more colours in and see what you can create.


Tags: css, development, css, development


Tweet WhatsApp Keep Upvote Digg Tumblr Pin Blogger LinkedIn Skype LiveJournal Like