Reputation: 99
I have a project where I am building slides described inside of an XML file but it requires to allow image positioning of the slides based on offset values.
Now I have Y offsets down pat, only problem now is that I require the ability to offset something in the X by an amount but still keep the %'age value behavior.
So basically is there anyway to have background-position's x start at 50% and then offset it by a pixel amount and keep the relative behavior of the %'age( 50% + offsetInPixels)?
Upvotes: 5
Views: 2215
Reputation: 75660
You can't do that with plain CSS (at this point in time, see Rich Bradshaw's answer).
You could accomplish that in javascript with something like:
var totalWidth = 960;
var xOffset = 10;
el.style.backgroundPosition = ((totalWidth/2) + xOffset) +"px 50px";
Upvotes: 3
Reputation: 623
I found another solution using CSS3. However, it requires the container to have a fixed size.
HTML:
<div id="example">Example</div>
CSS:
#example {
width: 200px;
height: 200px;
padding-left: 100px;
background-origin: content-box;
background-position: 10px 10%;
}
It's a bit of a hack I guess. Rather than starting the background-position from the left top corner of the border-box, it uses the content-box instead which has 50% (i.e. 100px) padding. Like I said, you will need to know the exact value of 50% padding because writing padding-left: 50%;
will be interpreted as 50% of the parent element.
If you need the full space inside this container you can put another <div>
into it with margin-left: -100px;
Upvotes: 0
Reputation: 72985
You can do this, but it isn't widely supported.
background-position: -moz-calc(50% - 20px) 0;
background-position: calc(50% - 20px) 0;
Currently (May 2011) this only works in Firefox 4 and IE9.
See http://caniuse.com/#calc for compatibility.
Upvotes: 4
Reputation: 8943
I'd say your best bet is sticking the background image as an image inside the containter... It's bit of a hack, but it works Also, consider (As Jesse said) adding overflow:hidden
if you don't want the bg pouring out.
<div id="main" >
<div id="bg"><img src="http://www.google.com/images/logos/ps_logo2.png"/> </div </div>
#main {
width:400px;
height:300px;
background-color:blue;
position:relative;
}
#bg {
margin-left: 10px;
position:absolute;
width:100%;
height:100%;
margin-left:50%;
}
demonstrated: http://jsfiddle.net/mhy3r/10/
Upvotes: 0