
CSS Trick: Sliding background color with a CSS transition
26 February 2024
·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:
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:
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.
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;
}
Apply the .slide-div class to the element you want to slide. And toggle the .slide-div-selected class onto the element when you want the background to slide in. I’ve also added a CSS variable to control the color of the background. So define the color on the element by adding some style like this:
<div class="slidy-div" style="--slide-color: #16a34a;"></div>
This is a complete example showing it working in Codepen. It uses vanilla Javascript to add and remove the .slide-div-selected class on the button click.
Thanks for reading!