Color background split effect with CSS Grid.

Create a "color background split" effect with CSS Grid.

It greatly simplifies the spacing adjustment gymnastics you need to do when using transforms to translate your element across both sections

Transcript

0:00 [background music]
Lecturer: 0:00 Last week, we shipped the new Thinkmill website, which is built with Astro and Tailwind CSS and I wanted you to show you a cool little CSS trick here that I've done for this news cards that you can see it sits halfway across the background split.

0:13 I thought it'd be fun to recreate this effect here in a Tailwind Play. I have two sections. One with the white background and one with the cyan background. We want to position our element here halfway across both colors. We're not going to have the element inside one of the section, but let's have it between the two.

0:30 Let's have a div with a class of relative, so we can anchor a background color stripes. Let's have a max width of lg, centered with mx-auto, a white background, p-8 rounded-lg. We'd also have a border with a width of two and maybe a shadow as well. Let's go with shadow-lg.

0:48 All right, that doesn't look that great, but that's going to work for us. Let's have a p tag with some lorem ipsum text. Now, instead of translating this thing over the line, we are going to have two bands that matches the top and the bottom background colors.

1:01 Inside the relative parent, I'm going to have an absolutely position element, which is going to occupy all the available space. This is going to be purely decorative. Let's add an aria-hidden attribute to it.

1:14 We want these to be a grid, which is going to have only one column and we're going to have two elements inside of it. If I add a class on the second of bg-purple-200, we can see that it covers exactly half the bottom height of our element. If the first one had bg-indigo-200, it would cover the other part.

1:33 Obviously, we want our paragraph here on top and that's behind the bands. I can fix that by adding a relative class. Actually, the correct class to use here would be isolate and that looks terrible right now. If I change the colors to match the backgrounds with bg-white and bg-cyan-100, check this out, now we have these pretty compelling results.

1:55 If I go to the preview mode, you'll see that our call out components doesn't take any space from the first section and the second section. If we had that element at the start of the blue section and then translated it up by its own half, we would have to figure out by how much to adjust the padding here.

2:10 The way we've done it, we preserve the padding level 24 that we have at the top and at the bottom, which I think makes that approach a pretty compelling solution.

More Tips