Brett Ryan
Brett Ryan

Reputation: 28255

Is there a way to position a background image relative to the centre of an element?

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

Answers (1)

3dgoo
3dgoo

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;
}

Demo

Upvotes: 17

Related Questions