简体   繁体   中英

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: http://imgur.com/a/zJgF4

 .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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM