***相对定位***
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<style type="text/css">
.box1{
width: 200px;
height: 200px;
background-color: pink;
}
.box2{
width: 200px;
height: 200px;
background-color: rgb(228, 21, 117);
/* 设置左外边距 */
/* margin-left: 200px; */
/* 设置上边距 ,box1为块元素,独占一行,所以box2相对box1移动*/
/* margin-top: 200px; */
/*
定位:
-定位是指将元素移动到页面指定的位置
通过定位可以任意摆放元素
-通过position设置定位
可选值:
-static:默认值,元素没有开启定位
-relative:开启元素相对定位
-absolute:开启元素绝对定位
-fixed:开启元素固定定位(绝对定位一种)
*/
/*
position: relative; 给box2设置相对定位
1.当开启相对定位不设置偏移量,元素不会产生变化
2.相对定位是相对于元素原来的位置
3.相对定位的元素不会脱离文档流,位置还在保留(脱离文档流是指没有他的位置了)
4.相对定位会使元素提升一个层级
5.相对定位不改变元素性质,块还是块,内联元素还是内联元素(没有宽高)
*/
position: relative;
/*
当开启定位(position属性值非static)时,
可以通过left right top bottom四个属性设置偏移量
left:元素相对于其定位位置(原来位置)设置的左偏移量
XXXXXXX(box左上角,左边原点)
两个偏移量就可以给元素定位,水平和垂直方向
*/
left: 200px;
top: 200px;
}
.box3{
width: 200px;
height: 200px;
background-color: rgb(126, 219, 49);
/* 设置margin-top ,负值上移*/
/* margin-top: -200px; */
}
.s1{
height: 200px;
width: 200px;
background-color: pink;
position: relative;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<span class="s1">相对定位不会使span脱离文档流</span>
</body>
</html>
***绝对定位***
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<style type="text/css">
/* *{
margin: 0;
padding: 0;
} */
.box1{
width: 200px;
height: 200px;
background-color: aqua;
}
.box2{
width: 200px;
height: 200px;
background-color: pink;
/*
position: absolute;开启绝对定位
绝对定位:
1.开启绝对定位,元素会脱离文档流
2.开启绝对定位,不设置偏移量,则元素位置不发生变化
3.绝对定位是相对于离他最近的开启了定位的祖先元素定位的
(一般开启子元素绝对定位,都会同时开启父元素的相对定位)
如果所有祖先元素都没有开启定位,那么相对于浏览器窗口定位
4.绝对定位会使元素提升一个层级
5.父元素开启相对定位,子元素宽度未设置会丢失宽度
6.绝对定位会改变元素的性质:
内联元素会变成块元素
块元素的宽度和高度都会默认被内容撑开
*/
position: absolute;
left: 20px;
top: 20;
}
.box3{
width: 200px;
height: 200px;
background-color: lightgreen;
}
.box4{
width: 300px;
height: 300px;
background-color: #fdf;
position: relative;
}
.s1{
height: 200px;
width: 200px;
background-color: pink;
position: absolute;
}
/*
position: fixed;
固定定位也是一种绝对定位,他的大部分属性和absolute一样
不同:
1.固定定位永远相对于浏览器定位,原点 top 0 left 0
2.固定定位会固定在浏览器窗口的每个位置,不会随浏览器移动变化
*/
</style>
</head>
<body>
<div class="box1"></div>
<div class="box4">
<div class="box2"></div>
</div>
<div class="box3"></div>
<span class="s1">绝对定位会使span脱离文档流</span>
</body>
</html>