一. 相对定位position:relative;
以自身为基准点进行定位。
a、不影响元素本身的特性;b、不使元素脱离文档流;
c、如果没有定位偏移量,对元素本身没有任何影响;
二. 绝对定位position:absolute;
a、使元素完全脱离文档流;
b、使内嵌标签支持宽高;
c、块属性标签内容撑开宽度;
d、如果有定位父级相对于定位父级发生偏移,没有定位父级相对于body发生偏移;
e、相对定位一般都是配合绝对定位元素使用;
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>范例</title>
<style>
div{font-size:20px;}
body{border:1px solid black;}
.box1{width:300px;height:300px; background:red; position:relative;}
.box2{width:200px;height:200px;background:blue;}
.box3{width:100px;height:100px;background:green; position:absolute;right:0;bottom:0;}
</style>
</head>
<body>
<div class="box1"><!-- 定位父级(干爹) -->
<div class="box2"><!-- 结构父级(亲爹) -->
<div class="box3"></div><!-- 绝对定位元素(儿子) -->
</div>
</div>
</body>
</html>
三. 固定定位
与绝对定位的特性基本一致,差别是始终相对整个文档进行定位;
问题:IE6不支持固定定位;
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>范例</title>
<style>
body{height:1500px;}
.box1{width:500px;height:100px; background:red; position:absolute;right:0;bottom:0;}
.box2{width:300px;height:300px;background:blue;position:fixed;right:0;bottom:0;}
</style>
</head>
<body>
<div class="box1">position:absolute;绝对定位</div>
<div style="width:200px; height:200px;border:5px solid black; position:relative;">
<span class="box2">position:fixed; 固定定位(始终在右下角)</span>
</div>
</body>
</html>
四. 定位元素位置控制
top / right / bottom / left 定位元素偏移量
五.定位元素层级
默认后者层级高于前者
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>范例</title>
<style>
div{font-size:20px;}
.box1{width:100px;height:100px; background:red; position:absolute; z-index:1;}
.box2{width:200px;height:200px;background:blue; position:relative;}
.box3{width:100px;height:100px;background:green;}
</style>
</head>
<body>
<div class="box1">div1</div>
<div class="box2">div2</div>
<div class="box3">div3</div>
</body>
</html>
本文详细解析了CSS中的四种定位方式:相对定位、绝对定位、固定定位及它们的特点与应用场景。介绍了定位元素的位置控制与层级关系,并通过示例代码帮助理解。
412

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



