简体   繁体   English

在div中将背景图像居中并在缩放时保持比例

[英]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. 我正在寻找的东西可以帮助我在调整浏览器窗口的高度(而不是宽度)时在div中“缩放” /“缩放”背景图像。 (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 我正在尝试实现的图像: 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; 您可以使用background-size: cover; so that the image always fills the container. 以便图像始终充满容器。

https://developer.mozilla.org/en/docs/Web/CSS/background-size 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. 您可以使用vh度量单位基于浏览器窗口的高度来控制图像容器的高度。

https://snook.ca/archives/html_and_css/vm-vh-units 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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