一、定位介绍
1.网页常见布局
2.运用场景
二、定位position
属性值
静态定位(不定位) | static |
相对定位(自恋型) | relative |
绝对定位(拼爹型) | absolute |
固定定位(死心眼型) | fixed |
方位属性
1、相对定位 position-relative(por)
特点:
- 还占着原来的位置
- 仍然保留原本标签的显示特点(div还是独占一行)
- 改变位置参照直接原本的位置
2、绝对定位 position-absolute(poa)
特点:
- 需要配合方位属性实现移动
- 默认相对于浏览器可视区域进行移动(父级有定位跟父级->子绝夫相)
- 在页面中不占位置 → 已经脱标
- 具备行内块特点
子绝夫相:
查找父级方式:就近原则找定位的父级(爷等)如果逐层找不到就相对于浏览器进行移动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.father{
/* position: relative; */
width: 500px;
height: 500px;
background-color: pink;
}
.son{
/* 工作中一般用relative */
position: relative;
width: 300px;
height: 300px;
background-color: blue;
}
.sun{
/* son有定位 */
position: absolute;
right: 20px;
width: 100px;
height: 100px;
background-color: green;
}
</style>
</head>
<body>
<div class="father">
<div class="son">
<div class="sun"></div>
</div>
</div>
</body>
</html>
子绝父相——居中问题:
问题:绝对定位的盒子不能使用左右margin auto 居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
/* 绝对定位的盒子不能使用左右margin auto 居中 */
position: absolute;
/* margin: 0 auto; */
/* 1.left 盒子移动到浏览器中间偏右 */
left: 50%;
/* 2.margin 盒子向右移动:自己宽度的一半 */
/* margin-left: -150px; */
top: 50%;
/* 2.位移:自己宽度高度的一半 */
transform: translate(-50%,-50%);
width: 300px;
height: 300px;
background-color: pink;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
3、固定定位 position-fixed(pof)
特点:
-
需要配合方位属性实现移动(left、top..)
-
相对于浏览器可视区域进行移动
-
在页面中不占位置 → 已经脱标
-
三、元素层级关系
层级关系:
更改层级:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 200px;
height: 200px;
}
.one {
position: absolute;
left: 20px;
top: 50px;
z-index: 1;
background-color: pink;
}
.two {
position: absolute;
left: 50px;
top: 100px;
background-color: skyblue;
}
/*
默认情况下, 定位的盒子 后来者居上 ,
z-index:整数; 取值越大, 显示顺序越靠上, z-index的默认值是0
注意: z-index必须配合定位才生效
*/
</style>
</head>
<body>
<div class="one">one</div>
<div class="two">two</div>
</body>
</html>