What the heck is background-attachment local
I recently came across
background-attachment: local because of this super amazing trick over on Smashing Magazine that adds a gradient on the sides of a table… only if the table is overflowing. It’s really neat, but while I knew of the
fixed values for
background-attachment, I’d never heard of
To understand what
local does, you need to know what
fixed do first, so a really quick primer on those:
scrollis the default - the background scrolls with the page as you’d expect
fixedmakes it so the image is fixed in place while the page scrolls past. It sort of gives you a parallax type of effect.
There is an issue with
scroll though, and that is, it doesn’t work as you’d expect it to if that isolated elment has a scrollbar. If that’s the case, it actually behaves like
fixed. Here is an example to illustrate what I mean.
Notice that, if you scroll the page the background works as you’d expect it to, but if you scroll within that element itself, it acts like a
fixed background. This is because the background of an element with
background-attachement: scroll scrolls with it’s border. When the entire page scrolls, the background moves along with it, but when you scroll within that element, the border of that element isn’t moving, hence the background doesn’t move either.
local to the rescue
This is what
local is for. It fixes the background to the content instead of the border of an element. Below is an example of all three at work. Notice that if you scroll the page, the first and last elements (
local respectively) behave the same… but then scroll inside the element. The one with
local is probably what you were after in the first place.
I’m happy I found this out before I ran into an issue with it, because it’s one of those CSS quirks that can really drive you bananas when you can’t figure out why it’s not behaving like you’d expect it to.
Don't want to miss an article?
While creating my YouTube videos, I come across a lot of fun snippits of information and little known CSS properties that aren't really worth building full videos about. I share the cool little things I run across (like you read in this post), as well as some design tips and tricks, with a new post every Sunday. Sign up below to never miss a post.