Html 如何在滚动内容中使用 100% CSS 背景图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19363978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:26:48  来源:igfitidea点击:

How to use 100% CSS background-image with scrolling content?

htmlcssbackground-image

提问by Kokodoko

I want to create a site with a background image that always fills the entire window, even if the content can scroll vertically.

我想创建一个背景图像始终填满整个窗口的站点,即使内容可以垂直滚动。

I have created this JSFiddleusing background-size:cover to scale the background-image to the window.

我创建了这个 JSFiddle使用 background-size:cover 将背景图像缩放到窗口。

It works, as long as the divs inside are smaller than the window. If you scroll vertically, the background image does not fill the page anymore, and shows a white/grey area instead.

只要里面的 div 小于窗口,它就可以工作。如果垂直滚动,背景图像不再填满页面,而是显示白色/灰色区域。

So my question is: how can I combine a 100% background image with scrolling content? This is my CSS:

所以我的问题是:如何将 100% 背景图像与滚动内容结合起来?这是我的 CSS:

html {
    height: 100%;
    margin:0px;
    background-color:#999999;
    background-image: url(http://s22.postimg.org/e03w9stjl/main_bg.png);
    background-position:center;
    background-repeat:no-repeat;
    background-size: cover;
}
body {
    min-height: 100%;
    margin:0px;
}
#appcontainer {
    position: absolute;
    background-color: rgba(255, 255, 255, 0.7);
    width:560px; height:2220px;
    left:20px; top:20px;
}

And HTML:

和 HTML:

<!DOCTYPE html>
<html>
<head></head>
<body>

    <div id="appcontainer">
        This div causes the background image to stop scaling to the page.
    </div>  

</body>
</html>

回答by Mr. Alien

Use background-attachment: fixed;

background-attachment: fixed;

Demo

演示

html { 
    height: 100%;
    margin:0px;
    background: url(http://www.freegreatpicture.com/files/147/18380-hd-color-background-wallpaper.jpg) no-repeat center center;
    background-size: cover;
    background-attachment: fixed;
}


Also, I didn't got why you are using position: absolute;on the wrapper element, generally you should be using position: relative;

另外,我不明白你为什么position: absolute;在包装器元素上使用,通常你应该使用position: relative;

回答by gvee

Add to your CSS:

添加到您的 CSS:

background-attachment: fixed;

回答by im_benton

    #appcontainer {
        position: absolute;
        background-color: rgba(255, 255, 255, 0.7);
        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;
        top: 0;
        right 0;
        left: 0;
        bottom 0;
    }