Is there any way to place the background image relative to the center of the element?

I have an element that I want to apply the background to, although I want the background image to be positioned based on its right coordinate.

I could use a div container to represent the background, although in this situation it is not very practical.

I currently have the following rule:

.myelem { background-image: url("myelem.png"); background-position: 5% 60%; background-repeat: no-repeat; } 

which for the most part works due to image size. If that were possible, I would like to have something indicating that the relative position of the background was middle instead of left .

+6
source share
1 answer

Css propoerty background-position takes center as the value:

 .myelem { background-image: url("myelem.png"); background-position: center center; background-repeat: no-repeat; } 

Or a shortened version:

 .myelem { background: url("myelem.png") center center no-repeat; } 

Update 1

There is no easy css way to set the background position to the center offset (either bottom or right).

You can add an addition to the actual image, use javascript to calculate the position after loading the page, 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 stage.

Using calc, you can 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

+11
source

All Articles