定位的基本内容:
position: relative;相对定位-
- 不影响元素本身特性(无论区块元素还是内联元素会保留其原本特性)
- 不会使元素脱离文档流(元素原本位置会被保留,即改变位置也不会占用新位置)
- 没有定位偏移量时对元素无影响(相对于自身原本位置进行偏移)
- 提升层级(用z-index样式的值可以改变一个定位元素的层级关系,从而改变元素的覆盖关系,值越大越在上面)
position: absolute;绝对定位
- 使元素完全脱离文档流(在文档流中不再占位)
- 使内联元素在设置宽高的时候支持宽高(改变内联元素的特性)
- 使区块元素在未设置宽度时由内容撑开宽度(改变区块元素的特性)
- 相对于最近一个有定位的父元素偏移(若其父元素没有定位则逐层上找,直到document——页面文档对象)
- 相对定位一般配合绝对定位使用(将父元素设置相对定位,使其相对于父元素偏移)
- 提升层级(同相对定位)
position: fixed;固定定位
- 除了相对于可视区偏移外与绝对定位一致
- ie6及更低版本不兼容
简单的定位应用:
固定定位:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style type="text/css">
body{height:2000px;}
.wrap{width:400px; height:400px; margin:100px auto; background-color:#ccc; position:relative;}
.box{width:150px; height:150px; background-color:red; position:fixed; right:0; bottom:0;}
</style>
</head>
<body>
<div class="wrap">
<div class="box"></div>
</div>
</body>
</html>
效果图:
绝对定位:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style type="text/css">
.wrap{width:400px; height:400px; background-color:#ccc; margin:100px auto; position:relative;}
.position{ position:absolute; font-size:30px; background-color:red; color:#fff; left:0; bottom:0;}
.box{width:100px; height:100px; background-color:blue;}
</style>
</head>
<body>
<div class="wrap">
<div class="position">position</div>
<div class="box"></div>
</div>
</body>
</html>
效果图:
定位应用:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style type="text/css">
.wrap{width:300px; height:300px; background-color:red; position:relative;}
.wrap div{width:50px; height:50px; background-color:#000; position:absolute;}
.box1{left:0; top:0;}
.box2{right:0; top:0;}
.box3{left:0; bottom:0;}
.box4{right:0; bottom:0;}
</style>
</head>
<body>
<div class="wrap">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
</div>
</body>
</html>
![](https://i-blog.csdnimg.cn/blog_migrate/2fc0f4070547573fa8ae13e23143ebab.png)