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
.
You need to specify the position of the image through the "center" value of the background shorthand property. Set the width of your image to "100%". In this example, we also specify the height and background-size of our image.
The background-position CSS property sets the initial position for each background image. The position is relative to the position layer set by background-origin .
The background-position property sets the starting position of a background image. Tip: By default, a background-image is placed at the top-left corner of an element, and repeated both vertically and horizontally.
Definition and Usage The background-position property sets the starting position of a background image. Tip: By default, a background-image is placed at the top-left corner of an element, and repeated both vertically and horizontally.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With