Positioning Offset Background Images

Avatar of Chris Coyier
Chris Coyier on (Updated on )

If you need to position a background-image in CSS 20px from the left and 10px from the top, that’s easy. You can do background-position: 20px 10px;. But what if you wanted to position it 20px from the right and 10px from the bottom?

Let’s also assume we don’t know the exact width and height of the element, which is likely, because fluid layouts and dynamic content. If we did, we could just do a little scratchpad math and use the normal background-position syntax.

A perfectly reasonable request, as they say. Here’s some ways to go about it.

The four-value syntax for background-position

This is the easiest way. You combine length values with any of top/right/bottom/left keywords (not center). So for our example:

background-position: right 20px bottom 10px;

Using this, you can offset a background-image from any of the four corners of an element.

Browser support, according to MDN: Chrome 25+, Firefox 13+, IE 9+, Opera 10.5+, Safari/iOS 7+. The biggest danger is Android.

I tested Android 4.0, 4.1, and 4.2 and it didn’t work. But Android 4.4 did support it.

Using calc()

You can continue to use the two-value syntax of background-position, but do it using lengths created via calc(). Like:

background-position: calc(100% - 20px) calc(100% - 10px); 

The browser support is slightly better, with Chrome back to 19+, Firefox back to 4+, and Safari back to 6+ (all prefixed).

Android stock browser had the same support as the four-value syntax above.

Using JavaScript

If you’re needing perfect browser support, I imagine the only way is JavaScript. Measure the height/width of the element, know the size of the background-image, then adjust the CSS as needed.

Using jQuery:

var el = $(".example"),
    bgWidth = 20,
    bgHeight = 20;

el.css({
  "background-position": (el.width()-bgWidth+10) + "px " + (el.height()-bgHeight-10) +  "px"
});

Demo

Here are all three ways: