Position a CSS background image x pixels from the right?

I think the answer is no, but can you position a background image with CSS, so that it is a fixed amount of pixels away from the right?

If I set background-position values of x and y, it seems those only give fixed pixel adjustments from the left and top respectively.


Solution 1:

background-position: right 30px center;

It works in most browsers. See: http://caniuse.com/#feat=css-background-offsets for full list.

More information: http://www.w3.org/TR/css3-background/#the-background-position

Solution 2:

It is possible to use attribute border as length from the right

background: url('/img.png') no-repeat right center;
border-right: 10px solid transparent;

Solution 3:

There is one way but it's not supported on every browser (see coverage here)

element {
  background-position : calc(100% - 10px) 0;
}

It works in every modern browser, but it is possible that IE9 is crashing. Also no coverage for =< IE8.

Solution 4:

As far as I know, the CSS specification does not provide for exactly what you're asking, outside of CSS expressions, of course. Working off the assumption that you don't want to use expressions or Javascript, I see three hackish solutions:

  • Make sure your background image matches the size of the container (at least in width) and set background-repeat: repeat or repeat-x if only the width is equalized. Then, having something appear x pixels from the right is as simple as background-position: -5px 0px.
  • Using percentages for background-position exhibits special behaviour that is better seen than described here. Give it a shot. Essentially, background-position: 90% 50% will make the right edge of the background image line up 10% away from the right edge of the container.
  • Create a div containing the image. Explicitly set the position of the containing element position: relative if not already set. Set the image container to position: absolute; right: 10px; top: 10px;, obviously adjusting the final two as you see fit. Place the image div container into the containing element.

Solution 5:

Try this:

#myelement {
  background-position: 100% 50%;
  margin-right: 5px;
}

Note though that the code above will move the whole element (not the background image only) 5px from the right. This might be ok for your case.