如何制作背景附件:固定;不拉伸图像?

时间:2014-10-23 12:36:53

标签: html css css3 background-image stretch

我想在使用滚动时移动背景图像,这是正常的 背景附件:固定; 但问题在于它正在拉伸图像,我无法再定位它。

http://jsfiddle.net/5c3b56a7/3/

.container{

    display: block;
    position: relative;
    width: 100%;
    margin:0 0 10px 0;
    padding:0;
    overflow:hidden;
    background-image:url('http://cdn.wallwuzz.com/uploads/background-fantasy-wallpaper-array-wallwuzz-hd-wallpaper-4338.jpg');
    overflow:hidden;
    background-repeat: no-repeat;
    background-position: center center;
    background-size:cover;
    min-height:350px;

}

.container2{
    background-attachment:fixed;
}

您可以在全屏幕上更好地查看问题 http://jsfiddle.net/5c3b56a7/3/embedded/result/

第一张图片是位置中心顶部

由于附件,第二个无法定位。

有没有办法做到这一点?

3 个答案:

答案 0 :(得分:4)

很遗憾,您无法一起使用background-attachment: fixedbackground-size: cover。 当background-attachment: fixed确定背景图片的行为与position: fixed元素相似时,background-size: cover会强制它相对于元素本身计算背景大小。

您仍然可以使用JavaScript来计算window.onscroll()事件中的背景位置。

答案 1 :(得分:2)

也许我误解了这个问题。这是我的变种,因为我意识到我想得到一个结果。

http://jsfiddle.net/p507rg68/light/

HTML

<body class="container2">
<div class="container"></div>
<div class="push"></div>
</body>

CSS

    .container{
    display: block;
    position: relative;
    width: 100%;
    margin:0 0 10px 0;
    padding:0;
    overflow:hidden;    
    background-repeat: no-repeat;
    background-position: center center;
    background-size:cover;
    min-height:350px;
    background-image:url('http://cdn.wallwuzz.com/uploads/background-fantasy-wallpaper-array-wallwuzz-hd-wallpaper-4338.jpg');
}

.container2{
    background-image:url('http://cdn.wallwuzz.com/uploads/background-fantasy-wallpaper-array-wallwuzz-hd-wallpaper-4338.jpg');
    background-size:cover;
    background-attachment:fixed;
    background-repeat: no-repeat;
    background-position: center center;
}
.push{
    margin-bottom:800px;
    display: block;
    width: 100%;
    height:1px;
}

答案 2 :(得分:0)

使用背景尺寸:设置图像尺寸!

相关问题