Is there a way to position a background image relative to the centre of an element?
css
Solution
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:
- HTML background image offset by x pixels from the center
- Offset a background image from the right using CSS
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;
}
Demo
Problem
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`.