<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>test</title>
<style type="text/css">
.test1 {
position: absolute;
width: 200px;
height: 200px;
background-color: yellow;
z-index: 5;
}
.test2 {
position: absolute;
width: 200px;
height: 200px;
background-color: red;
z-index: 3;
}
.test3 {
position: absolute;
width: 200px;
height: 200px;
background-color: black;
z-index: -1;
}
</style>
</head>
<body>
<div class="test1"></div>
<div class="test2"></div>
<div class="test3"></div>
</body>
</html>
复制代码
(2)如果盒子的z-index属性的值相等,那么后来者居上
复制代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>test</title>
<style type="text/css">
.test1 {
position: absolute;
width: 200px;
height: 200px;
background-color: yellow;
}
.test2 {
position: absolute;
width: 200px;
height: 200px;
background-color: red;
}
.test3 {
position: absolute;
width: 200px;
height: 200px;
background-color: black;
}
</style>
</head>
<body>
<div class="test1"></div>
<div class="test2"></div>
<div class="test3"></div>
</body>
</html>
复制代码
2、绝对定位的盒子水平居中
加了绝对定位的盒子不能通过margin :0 auto水平居中
复制代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>test</title>
<style type="text/css">
.test1 {
position: absolute;
left: 50%;
margin-left: -100px;
width: 200px;
height: 200px;
background-color: yellow;
}
</style>
</head>
<body>
<div class="test1"></div>
</body>
</html>
复制代码
先将盒子的左侧调整到浏览器的中间位置,然后再向左侧移动盒子宽度的一半
3、定位的特性
(1)绝对定位和浮动类似,行内元素添加绝对定位或固定定位后就可以直接设置高度或宽度
复制代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>test</title>
<style type="text/css">
.test1 {
position: absolute;
width: 200px;
height: 200px;
background-color: yellow;
}
</style>
</head>
<body>
<div class="test1"></div>
</body>
</html>
复制代码
(2)块级元素添加绝对定位或固定定位,如果不设置高度或宽度,默认大小是内容的大小
复制代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>test</title>
<style type="text/css">
.test1 {
position: absolute;
background-color: yellow;
}
</style>
</head>
<body>
<div class="test1">你好</div>
</body>
</html>
复制代码
(3)浮动的元素只会压住标准流的盒子,但是不会压住标准流里盒子的文字或图片,但是绝对定位或固定定位会压住标准流的所有内容
浮动:
复制代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>test</title>
<style type="text/css">
.test1 {
float: left;
background-color: yellow;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div class="test1"></div>
<p>早上好,今天是星期一</p>
</body>
</html>
复制代码
定位:
复制代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>test</title>
<style type="text/css">
.test1 {
position: absolute;
background-color: yellow;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div class="test1"></div>
<p>早上好,今天是星期一..................</p>
</body>
</html>
亚马逊测评www.yisuping.com