【问题标题】:CSS background image won't scaleCSS背景图像不会缩放
【发布时间】:2015-03-21 07:42:33
【问题描述】:

我正在尝试学习 html 和 css。现在我正在尝试让背景图像填充浏览器窗口,无论大小。 我已经用谷歌搜索了 100 次,每个页面几乎都说了同样的话。所以我复制了代码,但它对我不起作用。当我将浏览器设置为较小的尺寸时,背景图像会重复出现。我不希望我只是想让它填满窗口。 这是我的 CSS。

html {
background-image:url(background.jpg);
background-size: 100%;
background-image: no-repeat-y; }

在我做到 100% 之前,我尝试使用封面来代替,但这也不起作用。当窗口最大化时,图像是全屏的,但是当我调整它的大小时,图像会重复。

【问题讨论】:

  • 使用正文 {...} 而不是 html {...}
  • and background-image: no-repeat... 是错误的... 必须是 "background-repeat" ...
  • 我修复了不重复,现在图像将被截断,下面有空白。我复制了 NYCBilly 给我的 css,当我缩小浏览器窗口时,图像仍然无法缩放。 **没关系。出于某种原因,我错过了他输入的其他 100%。它现在正在工作。
  • 忽略它,很高兴它起作用了...... :)

标签: css


【解决方案1】:

使用background-size cover 就可以了:

html { 
  background: url(background.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

【讨论】:

    【解决方案2】:

    要缩放,你想要缩放的 CSS 需要在一个容器内部,即 HTML 容器内部的 BODY;试试这个:

    html {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }
    
    body {
      background-image:url(background.jpg);
      background-size: 100% 100%;
      background-repeat: no-repeat-y;
    }
    

    【讨论】:

      【解决方案3】:

      你需要给父div<body>指定一个100%的高度,这样任何一个高度为:100%的子div;将采用其父 div 的高度。这是一个例子:

      将您的内容包装在这样的父 div 中:

      <html>
        <body>
          <div class="wrapMeTight">
            ....Your page content....
          </div>
        </body>
      </html>
      

      并将其添加到您的 css 中:

      html, body    {
          height: 100%;
      }
      .wrapMeTight   {
          min-height: 100%;
          height: 100%;
          background-image: url (/img.jpg);
          background-size: cover;
          background-position: center center;
          background-repeat: no-repeat;
      }
      

      【讨论】:

        【解决方案4】:

        使用这个:

        <html>
          <head>
            <style type="text/css">
                body { background-image: url("background.jpg"); background-size: 100% 100%; background-repeat: no-repeat; height: 100vh; width: 100vh; }
            </style>
          </head>
          <body>
        
          </body>
        </html>
        

        【讨论】: