【问题标题】:Can't display full height of background image?无法显示背景图像的全高?
【发布时间】:2014-07-26 06:05:00
【问题描述】:

我希望将图像作为 div 中的背景,并且我希望它能够在调整浏览器大小时像标签内的图像一样响应并缩放。但是我在这里做错了,因为我的图像不是全高!?它的高度只有 80 像素。图像为 1500 x 650 像素。如果我将高度设置为 650 像素,那么它可以工作,但是尽管浏览器窗口较小,但它具有相同的高度!求一些帮助来解决这个问题。

<div id="introContainer">   
<h1>Test</h1>
</div>


#introContainer
{
background-image: url('bilderGuide/bilderLayout/bgStart2.jpg');
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}

【问题讨论】:

  • 您在哪些浏览器中测试它? Mobile Safari 有很多background-size: cover 的问题。这是您遇到问题的地方吗?
  • @RyanMitchell 不,我使用的是 Firefox。还有其他方法可以在 Safari 中使用吗?

标签: html css responsive-design


【解决方案1】:

它的高度为 80px,因为您的“div id="introContainer" 的内容只有那么大(div 会根据内容调整)。也许尝试给您的 div 一个固定的位置,底部:0px 和顶部:0px;它会根据窗口高度进行调整。这对我有用:

.coverDiv
{
    position: fixed;
    z-index: 0;
    top: 25px;
    left: 0px;
    right: 0px;
    bottom: 0px;
    padding: 0px;
    margin: 0px;
    border-style: none;
    border-width: 0px;
    background-size: cover;
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    overflow: hidden;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-clip: content-box;
    background-origin: border-box;
    background-image: url('../../Images/Backgrounds/HongKong.jpg');
}

【讨论】:

    【解决方案2】:

    使用 100% 高度。看到这个 JSBin:http://jsbin.com/huloxewo/1/edit?html,css,output

    在桌面上的 Chrome 和 Safari 上测试。

    CSS:

    body,html {
      height: 100%;
    }
    
    #introContainer
    {
        background-image: url('someImage.jpg');
        background-repeat: no-repeat;
        background-size: cover;
        background-position: center;
        height: 100%;
        max-height: 650px;
    }
    

    编辑:更新了我的回答以解决评论

    【讨论】:

    • 这覆盖了整个屏幕!我只是希望它以 650 像素的高度开始,然后在调整窗口大小时变得更小。
    • @3D-kreativ 试用更新后的 JSBin 链接。我已经更新了我的答案。你只需要添加一个max-height 属性。
    • 但是高度一直都是一样的!当我调整窗口大小时,我希望它变小。这不可能吗?
    • @3D-kreativ 当我调整窗口大小时它变得越来越小,但我还没有在 Firefox 上尝试过。您使用的是什么操作系统?
    • @3D-kreativ 刚刚在 Firefox 上尝试过,它也可以正常工作。当我减小窗口大小时图像会缩小,当我放大窗口时它不会超过 650 像素
    【解决方案3】:

    你可以用 Jquery 做到这一点,非常简单。

    优点:不需要知道图片的大小

    现场示例:http://jsbin.com/tukodame/1/edit?css,js,output

    CSS

    #introContainer
    {
        background-image: url('http://placehold.it/350x150');
        background-size: cover;
        background-position: center;
        height: 100%;
    }
    

    JS

    var img = new Image;
    img.src = $('#introContainer').css('background-image').replace(/url\(|\)$/ig, "");
    var bgImgHeight = img.height;  
    $('#introContainer').height(bgImgHeight);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      相关资源
      最近更新 更多