CSS扩展背景图片

7

我有一张大图作为页面的background-image。我想让图片的高度拉伸以填充页面的高度,同时也要居中显示。

background: black url("/image/background.jpg") no-repeat fixed center;
4个回答

16

background-size: cover在现代浏览器中可以解决问题 - 详见Mozilla的文档了解更多详情。

对于老版本浏览器(特别是较旧的IE版本),我使用像这个jQuery插件来模拟该行为,效果很好。


3
这个解决了:background-size: 1024px 100%; - JR Galia
很高兴能够指引你找到所需的东西 :) - Kelvin
我似乎无法使用“background”标签使其正常工作,但是“background-size: cover”似乎可以正常工作。 - ddavison

4

这里有一篇很好的文章:

http://css-tricks.com/perfect-full-page-background-image/

其要点是:

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

0
将此添加到CSS中。
{
background: black url("/image/background.jpg") no-repeat fixed center;
height: 100%;
width:100%
}

1
如果图像实际上比您要放置它的空间大,并且将对其进行裁剪,则Kelvin的答案是完美的,设置宽度和高度将拉伸图像。 - Scott Selby

0

我认为使用 div 是实现你想要的效果最简单的方法。

<div id="background">
    <img src="/image/background.jpg" class="stretch" alt="" />
</div>
    <style>
    #background {
        background-color:#000000;
        width: 100%; 
        height: 100%; 
        position: fixed; 
        left: 0px; 
        top: 0px; 
        z-index: -1;
    }

    .stretch {
        width:100%;
        height:100%;
    }
    </style>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接