【问题标题】:Fit background image to div使背景图像适合 div
【发布时间】:2012-01-02 06:24:08
【问题描述】:

我在下面的 div 中有一个背景图片,但是图片被截断了:

 <div style='text-align:center;background-image: url(/media/img_1_bg.jpg);background-repeat:no-repeat;width:450px;height:900px;' id="mainpage" align="center">

有没有办法在不切断的情况下显示背景图像?

【问题讨论】:

  • 图片比div大吗?
  • 是的,图片比 div 大
  • 背景图片:url(/media/img_1_bg.jpg);背景尺寸:包含;背景重复:不重复;

标签: html css background-image


【解决方案1】:

您可以使用background-size 属性实现此目的,现在是supported by most browsers

缩放背景图像以适应 div:

background-size: contain;

缩放背景图像以覆盖整个 div:

background-size: cover;

JSFiddle example

还有filter for IE 5.5+ support,还有vendor prefixes for some older browsers

【讨论】:

    【解决方案2】:

    如果您需要的是具有与 div 相同尺寸的图像,我认为这是最优雅的解决方案:

    background-size: 100% 100%;
    

    如果不是,@grc 的回答是最合适的。

    来源: http://www.w3schools.com/cssref/css3_pr_background-size.asp

    【讨论】:

    • 但这会拉伸图像...有没有办法在不拉伸的情况下适应背景图像?
    • 但是纵横比丢失了。
    • @Learner 如果您更改图像的尺寸而不裁剪图像,则纵横比将丢失 99% 的时间。这是常识。
    【解决方案3】:

    你可以使用这个属性:

    background-size: contain;
    background-repeat: no-repeat;
    

    然后你的代码是这样的:

     <div style="text-align:center;background-image: url(/media/img_1_bg.jpg); background-size: contain;
    background-repeat: no-repeat;" id="mainpage">
    

    【讨论】:

      【解决方案4】:

      你也用这个:

      background-size:contain;
      height: 0;
      width: 100%;
      padding-top: 66,64%; 
      

      我不知道你的 div 值,但我们假设你有这些。

      height: auto;
      max-width: 600px;
      

      同样,这些只是随机数。 为 div 制作具有固定宽度的背景图像(如果您愿意的话)可能非常困难,因此最好使用 max-width。实际上,用背景图像填充 div 并不复杂,只需确保以正确的方式设置父元素的样式,这样图像就有了可以进入的位置。

      克里斯

      【讨论】:

      【解决方案5】:
      background-position-x: center;
      background-position-y: center;
      

      【讨论】:

        【解决方案6】:

        尝试以下任何一种方法,

        background-size: contain;
        background-size: cover;
        background-size: 100%;
        
        .container{
            background-size: 100%;
        }
        

        【讨论】: