phazei
phazei

Reputation: 5437

How can I align the center of a background image with the left side of it's containing div?

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?

Upvotes: 0

Views: 90

Answers (1)

Kristers Dzintars
Kristers Dzintars

Reputation: 188

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/

Upvotes: 0

Related Questions