首页 > 技术文章 > HTML四种定位-绝对定位

yqPhare 2021-10-11 19:43 原文

绝对定位

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <title>Document</title>
 8     <style>
 9         .box1{
10             width: 200px;
11             height: 200px;
12             background-color: #bfa;
13            
14         }
15         .box2{
16             width: 200px;
17             height: 200px;
18             background-color: tomato;
19             /* 绝对定位
20             
21               --当元素的position设置为absolute
22               -绝对定位的特点:
23                  1、开启绝对定位后,如果不设置偏移量,元素的位置不会发生变化
24                  2、开启绝对定位后,元素会从文档流中脱离
25                  3、绝对定位会改变元素的性质,行内变成块,块的宽高被内容撑开
26                  4、绝对定位会使元素提升一个层级
27                  5、绝对定位元素是相对于其包含块进行定位的
28 
29                    包含块(containing block)
30                       -正常情况下:
31                         包含块就是离当前元素最近的祖先块元素
32                     -绝对定位的包含块:
33                      包含块就是离他最近的开启了定位的祖先元素
34                        如果所有的祖先元素都没有开启定位 则根元素就是它的包含块
35                        -html(根元素、初始包含块)
36               */
37           position: absolute;  
38           bottom: 0;
39           right: 0;
40         }
41         .box3{
42             width: 200px;
43             height: 200px;
44             background-color: greenyellow;
45            
46         }
47         .box4{
48             width: 400px;
49             height: 400px;
50             background-color: rgb(47, 61, 255);
51            position: relative;
52         }
53         .box5{
54             width: 300px;
55             height: 300px;
56             background-color: rgb(201, 14, 145);
57             /* position: relative; */
58            
59         }
60     </style>
61 </head>
62 <body>
63     <div class="box1">1</div>
64     <div class="box4">
65         4
66         <div class="box5">
67             5
68             <div class="box2">2</div>
69         </div>
70     </div>
71     
72     <div class="box3">3</div>
73 </body>
74 </html>
绝对定位是对于包含块而言的 其祖先元素应设置position:relative;
则会相对于对应已经设置position进行绝对定位,如果都没设置则会对于body,最后相对于HTML,也就是说位于页面的最左上角。

 


 

 

 

推荐阅读