相对定位的元素相对于最近定位的祖先。我找不到文档,这是为什么当此父级的溢出值设置为“ 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在上面的代码段中消失了?
答案 0 :(得分:1)
解决方案很简单。您没有为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>