absoulue與relative配合定位盒子居中問題

如何經過absoulue與relative配合把一個盒子或者是把2個div塊同時放到頁面中央部分?定位完成後爲何又須要margin-left與margin-top各往回走50%的長度,別忘記用z-index定位高度,請看下面代碼展現:
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6     <title>absoulue與relative配合定位盒子居中問題</title>
 7     <style type="text/css">
 8     *{
 9         margin: 0;
10         background-color: yellow;
11     }
12     /* 如何把-一個盒子放到頁面中央 */
13     .box{
14         width: 100px;
15         height: 100px;
16         background-color: blue;
17         position: absolute;
18         left: 50%;
19         bottom: 50%;
20         margin-top: -50px;
21         margin-left: -50px;
22         z-index: 2;
23     }
24     /*2.如何把2個div塊同時居中*/
25     .div1{
26         width: 500px;
27         height: 300px;
28         background-color: red;
29         position: absolute; ;
30         left: 50%;
31         top: 50%;
32         /*居中的只是一個點,因此須要往左走250,往上走150*/
33         margin-left: -250px;
34         margin-top: -150px; 
35          }
36     .div2{
37         width: 200px;
38         height: 100px;
39         background-color:green;
40         position: absolute;
41         top: 50%;
42         left: 50%;
43         margin-left: -100px;
44         margin-top: -50px;
45     }
46     </style>
47     <script>
48         window.onload=function(){
49             var obj=document.getElementById('ceshi')
50             obj.onclick=function(){
51                 console.log('123');
52                 alert('我一直在尋找找到了你便找到了整個世界')
53             }
54         }
55     </script>
56 </head>
57 <body>
58     <div class="box" id="ceshi"></div>
59     <div class="div1">
60         <div class="div2">
61         </div>
62     </div>
63 </body>
64 </html>
相關文章
相關標籤/搜索