Today we're going to play with dynamic linear gradients, and all the cool new background properties in CSS. Did you know you can influence how the background scrolls in an overflowing container? Did you know how to make flexible odd-even colored lines? We do. And by the end of this, so will you!
What are we talking about?
How does it work?
As you see in the example above, we've used a
linear-gradient to create a 1px line, which we
then scaled to the line-height in
background-size. To make the descenders of the font
poke through the line, we used
background-position to move the background up a tad.
You're thinking: "So far so good, nothing new under the sun, ho-hum, where's my eggnog?". But if we had left it
that that, adding
padding to a the box would completely break it. That's why the clever guys and gals at the
browser vendors cooked up the
background-origin property. With this property — when set to
content-box — the
browser starts the position calculation at the edge of the content-box instead of the padding-box, making our background flexible regardless of the padding. Neat huh?
But we're not quite done yet! By now it looks good, and it won't break if we add padding, but scrolling will
still ruin the whole thing. Luckily, there is something we can do about that: we simply set
background-attachment: local. This allows the background to scroll with our overflowing box, instead of being
attached to the page or being fixed.
What do you think about all this, Bob?
Maybe you won't use text-lines (or odd-even colored lines) that often, but the techniques described here have a far wider use. See the excellent demo by Lea Verou on how to use the background-attachment to indicate when there is more scrollable content.
Great, but can I use it today?
Yes, support is pretty solid (gold stars for everyone). One small blemish in this performance: Firefox does not
seem to support the "local" value for the
background-attachment, which breaks the scrolling in the examples
Show me the source!
Feel free to look around the differente source files we used for this example.