I know I can set a negative left position on a background image like this:
#element {
background: url(image.png) -20px 0 no-repeat;
}
That'll position the background image 20px to the left of the left edge of #element
, regardless of #element
's width.
But is there any way to set a negative right position, without giving #element
a fixed width (and then just setting a high positive left value)?
It's simply not true that this effect is impossible to obtain through simple CSS. There is no need to complicate your mark-up with unnecessary pseudo elements or multiple divs.
You can use the "calc" function in CSS to make the browser calculate 100% of the containers width and then add your negative margin to that like so (remember to add your negative margin to the 100% not subtract it):
background-position: calc(100% + 20px) 0;
Or if you prefer your mark-up in short-hand format:
background: url("image.png") calc(100% + 20px) 0 no-repeat;
This will position your background-image 100% (hereby obtaining the same effect as using background-position: right) from the left side of its container and by adding the 20px to that, you will obtain your negative right margin.
You can see a demo of how the function behaves in this jsFiddle: http://jsfiddle.net/58u665fe/
The "calc" function is supported by most major browsers, though support for IE9< lacks in certain cases. You can read more about which browsers support this function on http://caniuse.com/#feat=calc.