首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将一个div元素包含在另一个div元素中会破坏视差效果

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

Stack Overflow用户
提问于 2018-06-07 06:40:21
回答 1查看 67关注 0票数 0

以下是来自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元素中也是如此?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-07 07:01:23

这是直接的。

为什么它使用的是px值而不是百分比values

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

它一开始是有效的,因为它的父对象是body,它的height:100%意味着获取父对象的高度,这是一个html,它也有height:100%,它从视口中获取高度。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50730599

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档