Advertisement
Advertisement


Position a CSS background image x pixels from the right?


Question

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.

2016/12/06
1
323
12/6/2016 9:59:00 PM


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;
2014/09/14

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.

2015/02/05

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.
2010/07/07

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.

2012/01/16

You can do it in CSS3:

background-position: right 20px bottom 20px;

It works in Firefox, Chrome, IE9+

Source: MDN

2013/08/09

Source: https://stackoverflow.com/questions/3197250
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]