Reputation: 28255
I have an element that I wish to apply a background to, though I want the background image to be positioned based on its right co-ordinate.
I could use a container div to represent the background though it's not really practical in this situation.
I presently have the following rule:
.myelem {
background-image: url("myelem.png");
background-position: 5% 60%;
background-repeat: no-repeat;
}
Which for the most part works because of the size of the image. If it were possible I'd like to have something that specified that the relative position of the background was middle
instead of left
.
Upvotes: 10
Views: 16073
Reputation: 15794
The css propoerty background-position accepts center
as a value:
.myelem {
background-image: url("myelem.png");
background-position: center center;
background-repeat: no-repeat;
}
Or the shorthand version:
.myelem {
background: url("myelem.png") center center no-repeat;
}
Update 1
There is no simple css way to set the background-position to an offset of center (or bottom or right).
You could add padding to the actual image, use javascript to calculate the position after page load, add margin to the element as suggested in the following SO questions:
Alternatively you can use calc
to calculate the correct position. Although calc is not supported by all browsers at this point.
Using calc you could do something like this:
.myelem {
background-image: url("myelem.png");
background-position: 5% 60%;
background-position: -webkit-calc(50% - 200px) 60%;
background-position: calc(50% - 200px) 60%;
background-repeat: no-repeat;
}
Upvotes: 17