将div元素包含在另一个div元素中会破坏视差效果

时间:2018-06-06 22:40:21

标签: javascript html css

以下是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

正如我们所看到的,视差效应被彻底摧毁了。但这只发生在以百分比设置视差等级的高度时。如果将parallax类的height属性更改为像素,即使使用额外的div容器,视差效果也会再次开始工作

    height: 1000px;

为什么会这样? 有没有办法使用百分比获得视差效果,即使在显示的另一个div元素内?

2 个答案:

答案 0 :(得分:2)

这是直截了当的。

为什么它使用px值而非values

这是因为在设置百分比值时,浏览器会根据父级的高度来计算元素的高度,所以你将div包装在heightless之内,因此height:100%对div没有影响在那里,但它没有高度,所以它没有出现。

它首先起作用,因为它的父体是height:100%表示取其父级高度的体,即html也具有height:100%,它从视口中获取高度。

答案 1 :(得分:1)

很简单。您将<div class="parallax"></div>的高度设置为没有高度的父<div></div>的高度。所以,孩子没有高度。

这就是为什么它以像素为单位设置时的工作原理。知道了吗?

如果您需要任何帮助,请输入更多详细信息!

只要你的&#34;为什么&#34; ,这就是答案。

相关问题