0

It's really easy to align the center of a background-image with the center of the div via background-position. I can't see any way to align the center of a background-image with the left side of the div though.

I've tried playing with all sorts of different percentages for background-position, but I haven't been able to see how exactly the % is calculated outside of 0-100%. I know 0% is left of background with left of div, and 100% is right of background with right of div. But what is -50% or 200%? I think it's adjusting by a ratio of the width of the two items, which is pretty meaningless outside the range. I made this to try see if I could figure something out.

Anyone have any other suggestions to get the center of a background-image aligned the left side of the div it's set on?

phazei
  • 5,323
  • 5
  • 42
  • 46
  • let me know if the duplicate is enough detailed to help you figure out the calculation ... you will find all the needed relation and formula. – Temani Afif Nov 01 '18 at 22:12

1 Answers1

0

If I understood you correctly - you want to align background image center to be on left side of the div. Then maybe try this!

<div class="yourdiv" >
 <img class="yourbg" src="" >
</div>

<style>
*{
  margin: 0; padding: 0;
}
.yourdiv{
  width: 500px; height: 300px;
  overflow: hidden;
  position: relative;
}
.yourbg{
  width: 100%; height: auto;
  position: absolute;
  left: -50%;
}
</style>

Example here http://jsfiddle.net/e4w6stmc/

  • Yeah, that's pretty simple and what I did. I'm specifically referring to background-image though, so this isn't related to my question but a work around. I do see I wasn't as clear as I could have been with the question. Fixing that. – phazei Nov 02 '18 at 22:54