这是 w3schools 的原始工作示例
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body, html {
height: 100%;
}
.parallax {
/* The image used */
background-image: url('img_parallax.jpg');
/* Full height */
height: 100%;
/* Create the parallax scrolling effect */
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
</style>
</head>
<body>
<div class="parallax"></div>
<div style="height:1000px;background-color:red;font-size:36px">
Scroll Up and Down this page to see the parallax scrolling effect.
This div is just here to enable scrolling.
Tip: Try to remove the background-attachment property to remove the scrolling effect.
</div>
<div class="parallax"></div>
</body>
</html>
如果我将视差 div 包含在另一个内部,则效果将完全破坏。这是代码。
<div class>
<div class="parallax"></div>
</div>
你可以在这里做这个实验:https : //www.w3schools.com/howto/tryit.asp?filename=tryhow_css_parallax_percent
正如我们所看到的,视差效果被完全破坏了。但是这只发生在你以百分比设置视差类的高度时。如果您将视差类的高度属性更改为像素,即使使用额外的 div 容器,视差效果也会再次开始工作
height: 1000px;
为什么会这样?有没有办法使用百分比来获得视差效果,即使在另一个 div 元素中,如图所示?
这是直截了当的。
为什么它使用的是px
values 而不是百分比values
?
这是因为在设置百分比值时,浏览器会根据它的父元素的高度来计算元素的高度,所以你将 div 包裹在一个heightless
1 中,因此height:100%
不会影响 div 在那里但它没有高度,所以它不会出现。
它首先起作用,因为它的父级是主体,这height:100%
意味着采用父级的高度,即 html 也具有height:100%
从视口获取它的高度。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句