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 scroll and fixed values for background-attachment, I’d never heard of local before.

To understand what local does, you need to know what scroll and fixed do first, so a really quick primer on those:

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.

See the Pen background-attachment: scroll - wtf?! by Kevin (@kevinpowell) on CodePen.

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 (scroll and 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.

See the Pen background-attachment: local by Kevin (@kevinpowell) on CodePen.

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?

If you never want to miss out on any of my content? Subscribe to my newsletter!

It's one email every Sunday to keep you up to date with what I've been up to, plus I'll throw in some bonus stuff every now and then that I don't post anywhere else :)

    We won't send you spam. Unsubscribe at any time.