准备布局:
<!DOCTYPE html>
<html>
<head>
<style>
*{ margin:0; padding:0; }
.base-container{
width: 500px;
height: 500px;
background-color:lightgray;
border:1px dashed red;
}
.base-compare {
width:200px;
height:100px;
background-color:yellow;
border:1px solid purple;
}
.base-parent {
width:300px;
height:230px;
background-color:green;
}
.base-child {
width:200px; // 宽高同.base-compare
height:100px;
background-color:cyan;
border:1px solid purple;
}
</style>
</head>
<body>
<div class="base-container"><!--测试容器-->
<div class="base-compare">我是参考div</div>
<div class="base-parent parent"><!--父级div-->
<div class="base-child child">我是子级div</div>
</div>
</div>
</body>
</html>
(1)父级为relative,子级为absolute时:
.parent{
position:relative;
}
.child{
position:absolute;
top:30px; // 如果是百分比%,则相对于父容器的高度的百分比
left:20px;
// margin-top:30px; // 非%为单位时,等效,效果叠加;%为单位时,不等效!
// margin-left:20px; // 同上
}
(2)父级为static,子级为absolute时:
.parent{
position:static;
}
.child{
position:absolute;
top:50px; // 50%; (单位为%和非%)都是相对于最近的relative容器而言
margin-left: 50%; // 同上
}
(3)父级为fixed,子级为absolute时:
.parent{
position:fixed;
}
.child{
position:absolute;
top:100%; // 相对于父容器的高度百分比
right:10px; // 相对于父容器的右边
}