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

时间:2021-05-09 08:31:16

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块全部居中

 <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<style>
*{
margin:0px;
} .div1{
width:500px;
height:300px;
background: #f00;
position: absolute;
left:50%;
top:50%;
margin-top:-150px;
margin-left:-250px;
} .div2{
width:200px;
height:100px;
background: #0f0;
position: absolute;
top:50%;
left:50%;
margin-left:-100px;
margin-top:-50px;
}
</style>
</head>
<body>
<div class="div1">
<div class="div2"></div>
</div>
</body>
</html>