定位
为什么学习定位
1.定位可以让盒子自由的在某个盒子内移动位置或者固定屏幕中某个位置,并且可以压住其他盒子。
定位组成
定位:将盒子定在某个位置,所以定位也是在摆放盒子,按照定位的方式移动盒子。
定位=定位模式+边偏移
定位模式用于指定一个元素在文档中的定位方式,边偏移则决定了该元素的最终位置。
1.定位模式
定位模式决定元素的定位方式,它通过CSS的position属性来设置。其值可以分为四个
值 | 语义 |
static | 静态定位 |
relative | 相对定位 |
absolute | 绝对定位 |
fixed | 固定定位 |
边偏移
边偏移就是定位的盒子移动到最终位置,有top、bottom、left、right4个属性
边偏移属性 | 示例 | 描述 |
top | top: 80px | 顶端偏移,定义元素相对于其父元素上边线的距离 |
bottom |
bottom: 80px | 底部偏移量,定义元素相对于其父元素下边线的距离 |
left | left: 80px | 左部偏移量,定义元素相对于其父元素左边线的距离 |
right | right: 80px | 右部偏移量,定义元素相对于其父元素右边线的距离 |
静态定位static
静态定位是元素的默认定位方式,无定位的意思
语法:
选择器 {position: static;}
静态定位按照标准流特性摆放位置,他没有边偏移
静态定位在布局时很少用到
相对定位 relative
相对定位是元素在移动位置的时候,是相对于它原来的位置来说(自恋型)(以自己的上边和左边做x,y轴,向上下左右移动)
语法:
选择器 {position: relative;}
注意:
1.它是相对于自己原来的位置移动的(移动位置的时候参照点是自己原来的位置)
2.原来在标准流的位置继续占有,后面的盒子仍然以标准流的方式对待它。(不脱标,继续保留原来位置)
因此,相对定位并没有脱标,它最典型的应用是给绝对定位当爹的。
<!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>the second homework</title>
<style>
.box1 {
position: relative;
top: 100px;
left: 100px;
width: 200px;
height: 200px;
background-color: rgb(38, 135, 74);
}
.box2 {
width: 200px;
height: 200px;
background-color: rgb(225, 53, 122);
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>
绝对定位 absolute
绝对定位是元素在移动位置的时候,是相对于它祖先元素来说的。(拼爹型)
语法
选择器 {position: absolute;}
绝对定位的特点:
1.如果没有祖先元素或者祖先元素没有定位,则以浏览器为准定位(Document文档)
<!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>the second homework</title>
<style>
.father {
width: 500px;
height: 500px;
background-color: rgb(165, 202, 176);
}
.son {
position: absolute;
top: 10px;
right: 10px;
width: 200px;
height: 200px;
background-color: rgb(150, 166, 59);
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
2.如果祖先元素有定位(相对、绝对、固定定位),则最近一级的定位祖先元素为参考点移动位置。
<!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>the second homework</title>
<style>
.yeye {
position: relative;
width: 800px;
height: 800px;
background-color: rgb(118, 67, 199);
}
.father {
width: 500px;
height: 500px;
background-color: rgb(165, 202, 176);
}
.son {
position: absolute;
top: 10px;
right: 10px;
width: 200px;