我试图设置一个固定的 div 位置以便在底部查看它。但还需要定位相对于定位到距离父 div 10px 的子 div。 这是我的 HTML
<div class='container'>
<div class='inner'></div>
</div>
这是我的 CSS
.container{
position: fixed;
position: relative; //this one will apply by priority
bottom: 0;
height: 400px;
width: 400px;
}
.inner{
position: absolute;
top: 10px;
}
这段代码不会像我预期的那样工作。 我该怎么做。
最佳答案
任意位置accept static
作为绝对定位 child 的容器。你的问题是 bottom: 0
。只要视口(viewport)小于 .container
,容器的顶部就会超出屏幕。这使得子项看起来距离顶部不到 50px
。
使用 position: relative
只是忽略了 bottom: 0
,因为 0
的偏移量没有任何作用。
删除 bottom: 0
后:
.container {
position: fixed;
height: 400px;
width: 400px;
background: silver;
}
.inner {
position: absolute;
top: 50px;
}
<div class="container">
<div class="inner">inner</div>
</div>
关于html - div 位置固定但子元素也需要相对位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52598700/