【问题标题】:Stretch background image width but crop height拉伸背景图像宽度但裁剪高度
【发布时间】:2015-04-29 03:14:34
【问题描述】:

你如何制作背景img

  1. 水平拉伸窗口
  2. 有固定的高度
  3. 大于内容高度时裁剪高度(不要缩小)

目前我有实现 #1 和 #2 的代码,但我似乎无法实现 #3:

<img class="background" src="images/page-background.png"/>

html {
    position: relative;
}

.background {
    width: 100%;
    height: 2800px;
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
}

我尝试将imgoverflow: hidden 一起移动到div 中,但由于某种原因这不起作用:

<div class="background-wrap">
    <img class="background" src="images/page-background.png"/>
</div>

.background-wrap {
    position: absolute;
    width: 100%;
    height: 1000px;
    overflow: hidden;
    z-index: -1;
}

你将如何在 CSS / HTML(没有 JavaScript)中正确地做到这一点?

【问题讨论】:

标签: html css background


【解决方案1】:

您可以像这样在 div 上使用 css 背景图像:

.background-wrap {
 background: url(images/page-background.png) no-repeat;
 background-size: 100% 500px;
}

指定的背景大小; 在窗口中水平拉伸 100%,并具有 500 像素的固定高度(如果您希望图像高度与宽度成比例缩放,请将其更改为自动)。

【讨论】:

    【解决方案2】:

    对不起,伙计们,原来我完全忘了删除重复的背景&lt;img&gt;,这是我在将我的 HTML 拆分为多个文件(实际上是 PHP 文件,但这无关紧要)后留下的。

    为了将来参考,以下内容对我有用:

    <html>
        <head>...</head>
        <body>
           <div class="background-wrap">
               <img class="background" src="images/page-background.png"/>
           </div>
        </body>
    </html>
    
    html {
        position: relative;
    }
    
    .background-wrap {
        position: absolute;
        width: 100%;
        top: 0;
        bottom: 0;
        overflow: hidden;
        z-index: -1;
    }
    
    .background {
        width: 100%;
        height: 2800px;
        position: absolute;
        top: 0;
        left: 0;
        z-index: -1;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-09
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-21
      • 2016-06-06
      • 1970-01-01
      相关资源
      最近更新 更多