Html 使用css在div中调整背景图像的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6028737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:38:28  来源:igfitidea点击:

Resize background image in div using css

htmlcss

提问by user701254

Below css sets an individual background on two divs; the images repeat themselves if they do not fit into the div size.

下面css在两个div上设置一个单独的背景;如果图像不适合 div 大小,它们会重复。

How can I stretch the images using css to fit into space required by div ?

如何使用 css 拉伸图像以适应 div 所需的空间?

<style type="text/css">   
#contentMain {  
  margin-bottom: 5%; 
  margin-top: 10%;
  margin-left: 10%;
  margin-right: 10%;
  background: url( /jQuery/mypage/img/background1.png )
}  
#page1 {    
  background: url( /jQuery/mypage/img/background2.png )  
} 
</style> 

回答by Alp

Answer

回答

You have multiple options:

您有多种选择:

  1. background-size: 100% 100%;- image gets stretched (aspect ratio may be preserved, depending on browser)
  2. background-size: contain;- image is stretched without cutting it while preserving aspect ratio
  3. background-size: cover;- image is completely covering the element while preserving aspect ratio (image can be cut off)
  1. background-size: 100% 100%;- 图像被拉伸(可能会保留纵横比,具体取决于浏览器)
  2. background-size: contain;- 图像在保持纵横比的同时被拉伸而不切割
  3. background-size: cover;- 图像完全覆盖元素,同时保留纵横比(图像可以被截断)

/edit: And now, there is even more: https://alligator.io/css/cropping-images-object-fit

/edit:现在,还有更多:https: //alligator.io/css/cropping-images-object-fit

Demo on Codepen

Codepen 上的演示

Update 2017: Preview

2017 年更新:预览

Here are screenshots for some browsers to show their differences.

以下是一些浏览器的屏幕截图,以显示它们的差异。

Chrome

铬合金

preview background types chrome

预览背景类型镀铬



Firefox

火狐

preview background types firefox

预览背景类型火狐



Edge

边缘

preview background types edge

预览背景类型边缘



IE11

IE11

preview background types ie11

预览背景类型ie11

Takeaway Message

外卖留言

background-size: 100% 100%;produces the least predictable result.

background-size: 100% 100%;产生最不可预测的结果。

Resources

资源

回答by Bram B

i would recommend using this:

我建议使用这个:

  background-repeat:no-repeat;
  background-image: url(your file location here);
  background-size:cover;(will only work with css3)

hope it helps :D

希望它有帮助:D

And if this doesnt support your needs just say it: i can make a jquery for multibrowser support.

如果这不支持您的需求,只需说出来:我可以为多浏览器支持制作一个 jquery。

回答by Quentin

With the background-sizeproperty in those browsers which support this very new feature of CSS.

在那些支持 CSS 新特性的浏览器中使用background-size属性。