<div id="main" style="position: fixed">
<div id="inner" style="position: absolute">
</div>
</div>
如何使内部容器采用position:absolute
,而主容器采用position:fixed
,当两者都采用position: fixed
时。
当使用 fixed
、relative
或者 absolute
定位元素时,你需要定义 top
、right
、bottom
或 left
属性。
#main {
background: #000;
position: fixed;
height: 300px;
width: 200px;
left: 20px;
top: 10px;
}
#inner {
background: #f00;
position: absolute;
height: 100px;
width: 100px;
left: 10px;
top: 10px;
}
<div id="main">
<div id="inner">
</div>
</div>
<div id="main">
<div id="inner">
</div>
</div>
#main {
position: fixed;
width: 100px;
height: 100px;
border: 1px solid #000;
top: 50px;
left: 10px;
}
#inner {
position: absolute;
width: 10px;
height: 10px;
border: 1px solid #f00;
// top: 0px;
// left: 0px;
top: 10px;
left: 10px;
}
position:absolute
属性会根据它的父级div
的位置属性进行定位。
但是,position:fixed
属性总是根据用户视口来定位,无论元素位于何处。(与其父元素无关)
在此示例中,#main具有fixed
定位,并分配了200px
的left
属性。因此,它将从视口向左移动200px
,而#inner也具有left:100px
,但它将从父元素即#main向左移动100像素。如果内部元素也具有固定定位,则将从视口向左移动。 (取消代码注释以在codepen中查看其操作)
HTML
<div id="main">
<div id="inner">
</div>
</div>
CSS
#main {
position: fixed;
background: #cc3;
width: 500px;
height: 500px;
left: 200px;
}
#inner {
position: absolute;
width: 100px;
height: 100px;
background: #1d3;
left: 100px;
top:100px;
}
#main{
background:#ccc;
width:300px;
height:300px
}
#inner{
background:#fff;
text-align:center;
margin:20px;
padding:20px
}
<div id="main" style="position: fixed">
<div id="inner" style="position: absolute">
inner div
</div>
</div>
这里是 jsfiddle 代码: https://jsfiddle.net/awvov63a/