position属性值4缺一带你了解相对还是绝对抑或是固定定位

时间:2023-03-09 02:51:25
position属性值4缺一带你了解相对还是绝对抑或是固定定位

阿基米德说“给我一个支点,我能翘起整个地球”,在HTML页面中,给你一个坐标,可以把任何一个元素定位目标点,这就是定位!CSS有三种基本的定位机制:相对定位、绝对定位、固定定位,决定定位的position属性的值有static默认标准流,当然这个就不用多说了;fixed固定定位,releative相对定位,absoulte绝对定位,结论如下:1.定位配合坐标点top bottom left right;2.相对定位相对于自身位置自增或者自减,坐标起点是原来所在位置;3.absolute绝对定位找最近的position属性,没有的话,就找父集进行定位。代码展示:

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>position属性值4缺一带你了解相对还是绝对抑或是固定定位</title>
<style type="text/css">
div{
width: 200px;
height: 200px;
color: #fff;
}
.box1{
width: 120px;
height: 50px;
line-height: 50px;
background-color: darkviolet;
position: fixed;
bottom: 100px;
right: 50px;
text-align: center;
border-radius: 5px;
}
/* 固定定位,常见页面在线客服固定在某一个位置,怎么解决? */
/*配合定位 top bottom left right坐标点分2组 top bottom / left right*/
/*bottom: 100px; 底部往上100px*/
.box2{
background-color: red;
/* position: relative;
left:200px;
top:30px; */
}
/*相对定位*//*相对于自身位置自增或者自减,坐标起点是原来所在位置*/
/*向元素的原始上侧位置增加30像素。*/
/*向元素的原始左侧位置增加200像素。*/
.box3{
background-color: chartreuse;
/* position: absolute;
top: 100px;
left: 100px; */
}
/*发现box3添加绝对定位后位置飘到box2上面去了,box4上来了,box3的参考坐标点是body*/ .box4{
background-color: crimson;
}
.box5{
/* bottom: 300px;
right: 400px;
position: fixed; */
margin:0 auto;
position: relative;
background-color: darkmagenta;
}
.box6{
width: 100px;
height: 100px;
background-color:blue;
position: absolute;
top: 100px;
left: 100px;
}
/*结论absolute绝对定位找最近的position属性,没有的话,就找父集*/
</style>
</head>
<body>
<!--情景一绝对定位在外面-->
<div class="box1">hello!固定定位</div>
<!-- br*100 回车快捷键 展示如下-->
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div> <!--情景二绝对定位在里面-->
<div class="box5">
<div class="box6">绝对定位</div>
</div>
</body>
</html>

拓展:东北玛丽的小笔记该篇“position定位的四种属性