1.absolute:
<html>
<head>
<title>position</title>
<style>
#father {
width:200px;
height:100px;
position:reletive;
background-color:blue;
}
#son {
width:100px;
height:50px;
position:absolute;
background-color:gray;
top:20px;
left:40px;
}
</style>
</head>
<body>
<div id="father">
<div id="son">son</div>
</div>
</body>
</html>上面代码块中,son设置了position为absolute,father设置了position为relative,则会出现son相对father向下20px,向右偏40px;
2.
<html>
<head>
<title>position</title>
<style>
#father {
width:100%;
height:100%;
background-color:blue;
}
#son {
width:100px;
height:50px;
position:relative;
background-color:gray;
top:10%;
left:40px;
}
</style>
</head>
<body>
<div id="father">
<div id="son">son</div>
</div>
</body>
</html>上面的代码,son的position设置了relative,同事top为10%,则无论页面高度为多少,son始终距离son应该在的位置下方10%,fature没有设置padding,son没有设置magin,则10%应该是距离father最顶端10%,左右也是如此。
本文通过两个实例详细解析了CSS中absolute和relative定位方式的使用方法。第一个实例展示了如何使用absolute定位使元素相对于其最近的已定位父元素进行偏移。第二个实例则解释了relative定位下元素如何相对于其正常位置进行偏移。
436

被折叠的 条评论
为什么被折叠?



