Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shift background-position vertically by a certain value?

I have a container with its background image centered:

<div class="foo"></div>

.foo {
   background: white url(../image.jpg) no-repeat scroll center center / cover;
}

Is there any way to shift the position of the background image vertically by a fixed value (e.g. 10px) relative to its original position either with pure CSS or JS to get something like:

background-position: center (center - 10px);
like image 616
sdvnksv Avatar asked Jun 02 '26 17:06

sdvnksv


2 Answers

Try this calc

.foo {
   background-position: 50% calc(50% - 10px);
}
like image 134
akash Avatar answered Jun 05 '26 22:06

akash


You can try calc CSS function in combination with 50% value which means center:

background-position: center calc(50% - 10px);

Be careful, according to caniuse.com IE9 could have problems with that:

Partial support in IE9 refers to the browser crashing when used as a background-position value.

Another way is probably using background-origin property together with setting up the desired margin as a padding on the bottom (if you want to move the image up) or top (if you want to move the image down) of the box:

background-origin: content-box;
padding-bottom: 10px;
background-position: center center;

This looks uglier but at least should not have crashing problems with IE9.

like image 42
smnbbrv Avatar answered Jun 05 '26 21:06

smnbbrv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!