GetGalax
GetGalax

Reputation: 149

Centering a background-image within div and keep proportions when scaling

EDIT: Sorry, I realise it wasn't so clear, I'll try to clarify.

What I searching for is something that helps me to "zoom"/"scale" my background-image within the div when adjusting the height (not the width) of the browser window. (See attached image)

So far I've only managed to get the image to crop but still being centered using the code below.

Anyone have a solution for this?

Image of what I'm trying to achieve: https://i.sstatic.net/orMbu.jpg

.wrap {
  height: 50%
  background-color: red;
  overflow: hidden;
  position: relative;
  background-size: cover;
}

.image {
  position: absolute;
  left: 50%;
  margin-left: -1020px;
  background:url('https://placebear.com/2040/866') no-repeat;
  width:2040px;
  height:866px;
}
  <div class="wrap">
      <div class="image"></div>
  </div>

Upvotes: 0

Views: 110

Answers (1)

OrderAndChaos
OrderAndChaos

Reputation: 3860

I think this is what you are describing.

You can use background-size: cover; so that the image always fills the container.

https://developer.mozilla.org/en/docs/Web/CSS/background-size

This will at least scale the image to the correct proportions. Then you can scale the container how you want.

You can use vh units of measurement to control the height of the image container based on the height of the browser window.

https://snook.ca/archives/html_and_css/vm-vh-units

.wrap {
  height: 70vh;
  background-color: red;
  overflow: hidden;
  position: relative;
  background: url('https://placebear.com/2040/866') no-repeat;
  background-size: cover;
}
<div class="wrap">
</div>

Upvotes: 2

Related Questions