【问题标题】:CSS background image to fit height, width should auto-scale in proportionCSS背景图像以适应高度,宽度应按比例自动缩放
【发布时间】:2013-12-04 07:41:40
【问题描述】:

我希望背景图片适合 div 的高度,有办法吗? background-size:cover; 只适合宽度和高度自动缩放(我需要相反的效果)。 谢谢。

【问题讨论】:

标签: css


【解决方案1】:
background-size: contain; 

适合我

【讨论】:

  • 如果您的图像小于容器的高度,这将不起作用。 @Ajikan 下面的答案将适用于 (background-size: auto 100%;)
【解决方案2】:

试试

.something { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: -100;  
}

【讨论】:

    【解决方案3】:

    我知道这是一个旧答案,但对于其他正在寻找这个的人来说;在你的 CSS 中尝试:

    background-size: auto 100%;
    

    【讨论】:

    • 这对我来说非常有用。特别是在我希望仅根据高度调整背景图像大小的情况下。
    • 这需要min-height: 100% 来处理“比背景高”的情况。
    • 非常有帮助!在我的例子中,我使用了变量background-size: auto auto;,这样无论哪个轴更小(宽度或高度),它都会保持在那个范围内。否则在调整页面大小时它会被剪裁。
    【解决方案4】:
    body.bg {
        background-size: cover;
        background-repeat: no-repeat;
        min-height: 100vh;
        background: white url(../images/bg-404.jpg) center center no-repeat;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
    }   
    Try This
    
        body.bg {
        	background-size: cover;
        	background-repeat: no-repeat;
        	min-height: 100vh;
        	background: white url(http://lorempixel.com/output/city-q-c-1920-1080-7.jpg) center center no-repeat;
        	-webkit-background-size: cover;
        	-moz-background-size: cover;
        	-o-background-size: cover;
        }	
        <body class="bg">
    
    
        	
        </body>

    【讨论】:

      【解决方案5】:

      我刚刚遇到了同样的问题,这对我有帮助:

      html {
          height: auto;
          min-height: 100%;
          background-size:cover;
      }
      

      【讨论】:

      • 其他答案似乎无法正确处理both“大于背景”和“高于背景”的情况,或者涉及过多的 CSS。这个效果很好(顺便说一句,height: auto; 甚至不需要,只需使用background-size: cover; min-height: 100%)。
      • 这是一个非常简单的答案,对于我已经尝试在网站上解决数周的错误。我不明白为什么height 不能像我一直在做的那样使用,但无论如何,谢谢。作为记录,我发现在 HTML 元素本身上设置 background-size:cover 很好。
      猜你喜欢
      • 2012-03-04
      • 2014-01-18
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      • 2019-08-03
      相关资源
      最近更新 更多