Title image of CSS Trick: Sliding background color with a CSS transition

CSS Trick: Sliding background color with a CSS transition

26 February 2024

·
CSS

Small animations can really make a web app feel great to use. CSS transitions are the easiest way to do this. They’re so easy even a developer like me can be mistaken for a front end pro. I guarantee you will make your product owner melt if you add a couple of these to an existing boring web app.

Saying that there are a few little tricks to getting certain CSS properties to animate in the way we want. This post is about one of these: a sliding background color. We want the background color of an element to change by sliding in from the side.

The sliding background effect:

Sliding background effect in action

Explanation

CSS transitions allow us to change CSS properties smoothly over time. To change the background color we might add a transition on the background-color property. But that would fade in the color instead of the slide we want. To get a slide we need to be more creative.

To get a clean slide we need to transition the background-position property. But before that we need to setup the background. Setting the background width to 200% of the target means we always have background when we move it. Using a linear-gradient for the background image gives a clean slide from one color to another.

This setup gives a clean slide from white to blue:

Background color setup

And now the position. Starting the background position off to the left and then transitioning it back to center will give us a slide. This is how it looks moving from background-position: 100% 0; to background-position: 0 0.

Sliding background explainer

Code

Only two classes are needed for this effect. The base class and the conditional selected class:

.slidy-div {
  transition: background-position 0.5s;
  background-size: 200% 100%;
  background-image: linear-gradient(to right, var(--slide-color) 50%, white 50%);
  background-position: 100% 0;      
}

.slidy-div-selected {
  background-position: 0 0;
}

Here’s the CSS in action with some basic Javascript to toggle the selected class: