I like how percentage background-position works

Avatar of Chris Coyier
Chris Coyier on

I learned something the other day when we were fleshing out the background properties in the Almanac. It’s such an intuitive thing, that I guess I just never stopped to think about it before.

By default, background-position is 0 0, the top left corner. Now imagine you set it to 50% 0. That background image is now center top. It figures out the size of that image, and positions the center of it at the center of the element.

That’s different than if you, say, had an <img> and positioned it at left: 50%; in that scenario, the left edge of the image would be at the halfway point. If you want to center it, you’ll need to pull it back to the left (negative translate or negative margin).

Here’s a visualization of that difference:

See the Pen The Difference Between background-position and left by Chris Coyier (@chriscoyier) on CodePen.

So if you set something like background-position: 25% 25%, that positions the image such that 25% of the way across itself aligns with 25% of the way across the element. And the same vertically.

Nothing revolutionary here. I just think it’s cleverly designed. You don’t have to think about it much, because it just works like you would assume it works. Of course if I set right top for the background-position the image is drawn in the right top corner. I don’t think about how the browser must be calculating the image size and the element size and aligning axises at those positions.