CSS Radial Gradient Experiments

aka How I made this site's background

CSS Radial Gradient Experiments

While developing this site’s theme, I decided not to have an image at the top of every page. So I needed a background with enough detail to compensate. I also wanted the background to be responsive and not use image files. And I wanted it to look a bit different from page to page. Here’s how I did it with a magic number, radial-gradient, and the nth-child selector.

Inspired By

I’ll tell you now the magic number isn’t 3 or 42. And I would never have thought to use hard-edged gradients if Kedar’s post hadn’t landed in my feed.  Once it did, I discovered plenty of other people doing cool things with gradients.

Sometimes it just takes landing on the right idea at the right time <3

Positioning Radial Gradients

I had a terrible time getting my head around how to position radial-gradient – keywords like closest-side and farthest-corner aren’t intuitive for me.

I find it much easier to use percentages – and sometimes pixels. The CodePen below is how I figured it out and it helps explain how I made this site background.

The most important thing to know is that radial-gradient is proportional to its element.

When you declare a gradient’s size as a percentage, it’s relative to the element’s width.

This unlocks the magic number – an ellipse sized at 70% will just about touch all 4 edges of it’s element.

The HTML

Looking at the example above, I’m sure you’ve figured out that I’m somehow alternating a series of ellipses sized at 70%. You’re right! But there’s a bit more to it.

For this background to work, you need well-structured HTML. Each of my pages has an <article> with multiple<section> tags which is where the gradients are used.

The important part is to use <section> for all immediate children.

Well, I suppose you could use a <div> with a .class , but I think <section> makes more sense semantically, so I use it.

The SCSS

Below is a full demo of this site’s background. It uses 4 alternating gradients. The hardest bit was figuring out how to set up the repeating pattern, so I’ll condense it here:

article section:nth-child(4n+1) {}
article section:nth-child(4n+2) {}
article section:nth-child(4n+3) {}
article section:nth-child(4n) {}

Wrap

So now you know the magic number is 70%, how to read at 30% 60%, and how to use the nth-child selector to set up a repeating pattern.

Here’s some I did with linear-gradient. I’m sure a more creative person could do way better, but they are super fun to make and to resize 🙂

See the Pen CSS Gradient Backgrounds by Lisa (@ljburton) on CodePen.

Post Comment

Your email address will not be visible to others or sold to 3rd parties.