如何将背景图像拉伸到填充div

时间:2013-10-31 12:26:35

标签: css html

我想在我的网站上添加封面图片。我在页面顶部有一个div标签。我已将div标签的宽度设置为80%,将高度设置为auto。我想添加一个图像作为该div的背景。该图像宽度应根据div的宽度拉伸。图像高度应根据其新宽度(拉伸宽度)自动更改。

5 个答案:

答案 0 :(得分:3)

.style1 {
        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;
}

为什么你不使用模式而不是瘫痪网络?

答案 1 :(得分:1)

您可以使用CSS3 background-size属性。

http://jsfiddle.net/9UNVT/

<强> CSS

.background { border:1px solid red; width:500px; height:500px; background:url('http://placehold.it/100x100') 0 0 no-repeat; }
.cover { background-size:cover; }

<强> HTML

<div class="background">
    no-cover
</div>

<div class="background cover">
    cover
</div>

注意:我刚刚使用过background-size,但如果您想让它更灵活,您可能需要包含所有供应商前缀版本。

答案 2 :(得分:0)

.style1 {
        background: url(images/bg.jpg) center center;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
-ms-background-size: cover;
        background-size: cover;
}
.style1 {
background-size:100% 100%
}

答案 3 :(得分:0)

您最好尝试此代码..背景图片将根据宽度拉伸。

<div class="container">
</div>


.container {
width:80%;
background:url(image.png) no-repeat center center;
background-size:100% 100%;
}

答案 4 :(得分:-2)

您始终可以将图像设置为背景图像:

.div {

background-image:url('image.jpg');

}