div定位中position的使用说明:
共四个选项:static、absolute、relative和fixed。其中absolute和relative最为常用。
使用absolute定位:
position:absolute;表示字块已经不再属于父块了,字块左边框的位置是相对于页面<body>左边的边距,字块上边框是相对于<body>上边框的位置。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div1{width:300px;height:80px;border:1px solid blue;margin-top:20px;margin-left:30px;}
.div2{width:170px;height:30px;border:1px solid blue;background-color: yellow;
position:absolute;top:40px;left:60px;}
</style>
</head>
<body>
<div id="div1">
<div class="div2">div绝对定位</div>
</div>
</body>
</html>
使用relative定位:当position:relative时,与absolute完全不同,这时字块是相对于其父块来进行定位的需要设置top和left两个值。提示:top或left的值除了px之外还可以设置成百分比。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div1{width:300px;height:80px;border:1px solid blue;margin-top:20px;margin-left:30px;}
.div2{width:170px;height:30px;border:1px solid blue;background-color: yellow;
position:relative;top:80px;left:60px;}
</style>
</head>
<body>
<div id="div1">
<div class="div2">div绝对定位</div>
</div>
</body>
</html>
空间位置z-index该属性用于调整定位时重叠块的上下位置
z-index的值大的页面位于其值小的的上方(离我们越近值越大)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div1{width:300px;height:80px;border:1px solid blue;margin-top:20px;margin-left:30px;z-index: 20;}
.div2{width:170px;height:30px;border:1px solid blue;background-color: yellow;
position:absolute;top:80px;left:60px;z-index: 1;}
.div3{width:180px;height:40px;border:1px solid blue;background-color: yellow;
position:absolute;top:90px;left:70px;z-index:4;}
</style>
</head>
<body>
<div id="div1">
<div class="div2">div绝对定位</div>
<div class="div3">块2</div>
</div>
</body>
</html>