码迷,mamicode.com
首页 > 其他好文 > 详细

absoulue与relative配合定位盒子居中问题

时间:2020-02-22 22:00:44      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:高度   margin   OLE   abs   box   var   utf-8   yellow   一个   

如何通过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>

absoulue与relative配合定位盒子居中问题

标签:高度   margin   OLE   abs   box   var   utf-8   yellow   一个   

原文地址:https://www.cnblogs.com/dhnblog/p/12347127.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!