Html 带有垂直滚动的整页背景图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18050611/
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
Full page background image with vertical scrolling
提问by Erik Fischer
I'm trying to create a page where the background image is responsive to your browser's screen size. However, I need content under that image such that if the person scrolls down, the background image ends.
我正在尝试创建一个页面,其中背景图像响应浏览器的屏幕大小。但是,我需要该图像下的内容,以便如果该人向下滚动,则背景图像结束。
It's hard to explain so I've tried to create an image to make it clearer:
很难解释,所以我尝试创建一个图像以使其更清晰:
回答by tb11
Try this Fiddle:
试试这个小提琴:
HTML:
HTML:
<div class='image'></div>
<div class='content'>Content</div>
Use absolute positioning to make the background image the same size as the screen, and put the content after, with a top
of 100%
:
使用绝对定位使背景图片与屏幕大小相同,将内容放在后面,用a top
of 100%
:
body {
margin:0;
}
.image {
position:absolute;
width:100%;
height:100%;
background:green;
background-image:url('some-image.jpg');
background-size:cover;
}
.content {
position:absolute;
width:100%;
top:100%;
height: 100px;
}
回答by Zach Saucier
There is no need for position: absolute
as tb11 suggests.
没有必要position: absolute
像 tb11 建议的那样。
You can simply set the height of the viewport using viewport units or by setting the height for the html, body, and image elements.
您可以使用视口单位或通过设置 html、body 和图像元素的高度来简单地设置视口的高度。
Using vh
- Demoand support chart:
body { margin: 0; }
.image {
width:100vw;
height: 100vh;
background: green;
background-image: url('some-image.jpg');
background-size: cover;
}
If you can't use vh
, you'll have to set the height of the html and body elements as well so that you can use percents - Demo:
如果您不能使用vh
,则还必须设置 html 和 body 元素的高度,以便您可以使用百分比 -演示:
html, body, .image { height: 100%; }
body { margin: 0; }
.image {
width:100%;
background: green;
background-image: url('some-image.jpg');
background-size: cover;
}