Reputation: 28783
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)?
Upvotes: 7
Views: 16154
Reputation: 216
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.
Upvotes: 20
Reputation: 449
There's another way to achieve this without changing your markup:
using the :after pseudo-selector you can add an image to the right of any block although is not the same as an actual css background
so you can do:
#element {
position: relative;
}
#element:after{
content: "";
background: transparent url(image.png) 0 0 no-repeat;
position: absolute;
right: -20px;
top: 0;
height: 50px /*add height of your image here*/
width: 50px /*add width of your image here*/
z-index: 1;
}
#element *{
position: relative;
z-index: 2; /*this makes sure all the "background image" doesn't sit above the elements*/
}
Upvotes: 2
Reputation: 6698
What you're wanting to do is not possible in the way you want to do it.
A fix might be to create a parent div with a position: relative;
attribute and then z-index another div behing a div that holds your content.
<style>
#parent {
position: relative;
}
#background {
background: url(img.png) top left no-repeat;
position: absolute;
top: 0;
left: -20px;
}
#content {
position: absolute;
top: 0;
left: 0;
}
</style>
<div id="parent">
<div id="background"></div>
<div id="content"></div>
Upvotes: 3