相对定位的元素是相对于最近定位的祖先。我找不到的文档是,为什么当这个父对象的overflow被设置为一个不是"visible“的值时,它的相对定位的子对象的位置似乎会受到影响。
我在这里复制了这段代码,试着取消注释第12行:
html {
/* this is required to reproduce the issue */
overflow-y: auto;
}
body {
background-color: hotpink;
position: relative;
margin: 10px;
/* UNCOMMENT LINE 12 AND #APP WILL DISAPPEAR. WHY? */
/* overflow-y: auto; */
}
#app {
position: absolute;
background-color: black;
left: 0;
top: 0;
width: calc(100vw - 20px);
height: calc(100vh - 20px);
color: white;
}<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
Uncomment line #12 and I will disappear. Why?
</div>
<script src="src/index.js"></script>
</body>
</html>
下面是完全相同的代码片段,但是重新启用了第12行:
html {
/* this is required to reproduce the issue */
overflow-y: auto;
}
body {
background-color: hotpink;
position: relative;
margin: 10px;
/* UNCOMMENT LINE 12 AND #APP WILL DISAPPEAR. WHY? */
overflow-y: auto;
}
#app {
position: absolute;
background-color: black;
left: 0;
top: 0;
width: calc(100vw - 20px);
height: calc(100vh - 20px);
color: white;
}<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
Uncomment line #12 and I will disappear. Why?
</div>
<script src="src/index.js"></script>
</body>
</html>
这是一个代码沙箱,你可以使用它:https://codesandbox.io/s/falling-cherry-pce0t?file=/src/styles.css
我在这里创建了一个屏幕录制:https://app.usebubbles.com/dtb9vyNadHq8eMm2YsbfAQ/comments-on-codesandbox-io/
我知道粘性定位的元素是通过滚动机制粘连到最近的祖先的,滚动机制被定义为溢出设置为“可见”以外的值的元素。我想知道这是不是有某种关联。
为什么在定位的祖先上设置溢出会影响其相对定位的子代的位置?也就是说,为什么在重新启用第12行时,#app会在上面的代码片段中消失?
发布于 2020-08-02 14:40:52
解决方案很简单。您未指定body元素的高度。因为#app有position: absolute,所以父元素没有定义的元素,也没有相对元素,父元素折叠并达到高度0。
而且,由于body没有高度,所以不能溢出它。您只能使用#app滚动它溢出的内容。
html {
overflow-y: auto;
}
body {
background-color: hotpink;
position: relative;
height: calc(100vh - 20px);
width: calc(100vw - 20px);
margin: 10px;
}
#app {
position: absolute;
background-color: black;
color: white;
top: 0;
left: 0;
bottom: 0;
right: 0;
overflow-y: auto;
}<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
This paragraph will overflow in y direction once text fills the container.
</div>
</body>
</html>
https://stackoverflow.com/questions/63212128
复制相似问题