css3-7 如何让页面元素水平垂直都居中(元素定位要用css定位属性)

css3-7 如何让页面元素水平垂直都居中(元素定位要用css定位属性)

一、总结

一句话总结:元素定位要用css定位属性,而且一般脱离文档流更加好操作。先设置为绝对定位,上左都50%,然后margin上左负自己宽高的50%。

1、如何让页面元素水平垂直都居中?

先设置为绝对定位,上左都50%,然后margin上左负自己宽高的50%。

16             position: absolute;
17             left:50%;
18             top:50%;
19             margin-top:-150px;
20             margin-left:-250px;

2、所有的定位都可以设置为绝对定位么?

所有的定位设置为绝对定位,脱离文档流,然后该怎么方便怎么设置

16             position: absolute;
17             left:50%;
18             top:50%;
19             margin-top:-150px;
20             margin-left:-250px;

3、绝对定位如何设置距浏览器上左的距离?、

left和top属性,因为这是定位的属性

17             left:50%;
18             top:50%;

4、在设置了left和top之后,如何再设置自己的偏移?

用margin属性,margin-left和margin-top

19             margin-top:-150px;
20             margin-left:-250px;

二、如何让页面元素水平垂直都居中

1、相关知识

定位:
1.position:absolute;
2.position:relative;

绝对定位和相对定位:
1.相同点
1)脱离文档流,都在文档流的上方

2.不同点
1)绝对的坐标系在浏览器的左上角,相对的坐标系在自己的左上角
2)绝对不占位,相对占位

2、代码

两个div块全部居中

 1 <!doctype html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>index</title>
 6     <style>
 7         *{
 8             margin:0px;
 9         }
10     
11 
12         .div1{
13             width:500px;
14             height:300px;
15             background: #f00;
16             position: absolute;
17             left:50%;
18             top:50%;
19             margin-top:-150px;
20             margin-left:-250px;
21         }        
22 
23         .div2{
24             width:200px;
25             height:100px;
26             background: #0f0;
27             position: absolute;
28             top:50%;
29             left:50%;
30             margin-left:-100px;
31             margin-top:-50px;
32         }
33     </style>
34 </head>
35 <body>
36     <div class="div1">
37         <div class="div2"></div>
38     </div>
39 </body>
40 </html>
 
原文地址:https://www.cnblogs.com/Renyi-Fan/p/9233018.html