【学习笔记】块级元素水平垂直居中方法

本文以<div>元素为例css

本文转载css3

1.已知块级元素的宽和高,使用绝对定位absolute和外边距实现水平垂直居中。flex

父元素position:relative,子元素position:absolute;top:50%;left:50%;margin-top:-height/2;margin-left:-width/2;spa

(思想:先把块级元素中的左上角定位到父元素的中心,而后再向上向左偏移自己的一半,就达到了是自己的中心居中的目的)code

效果图以下:orm

 

 

代码:blog

 1 <div class="box">
 2     <div class="center-box1">
 3         <p>【第一种方法】知道长和宽,使用绝对定位+外边距设定水平垂直居中</p>
 4     </div>
 5 </div>
 6 
 7 .box {
 8     background: #6c94be;
 9     width: 100%;
10     height: 450px;
11     position: relative;  
12 }
13 .center-box1 {
14     position: absolute;
15     top: 50%;
16     left: 50%;
17     margin-top: -100px;
18     margin-left: -100px;
19     width: 200px;
20     height: 200px;
21     background: #5B83AD;
22 }

2.使用css3 display:flex(IE存在兼容性问题)it

父元素样式属性display:flex;子元素使用margin:auto。这种方式在子块级元素宽高不肯定的时候(宽高会自适应为其里面内容的宽高)依然能够使用。io

效果图以下:form

代码:

 1 <div class="box">    
 2     <div class="center-box2">
 3         <p>【第二种方法】使用css3样式属性display:flex设定水平垂直居中</p>
 4     </div>
 5 </div>
 6 
 7 .box {
 8     background: #6c94be;
 9     width: 100%;
10     height: 450px;
11     display: flex;
12 }
13 .center-box2 {
14     margin: auto;
15     width: 200px;
16     background: #5B83AD;
17 }

3.使用绝对定位+CSS3 transform(因为transform中translate偏移的百分比都是相对于自身而言的,因此不像方法一种那样必须知道子元素的宽高才行,可是对于IE只有IE9+才支持)

效果图以下:

代码:

 1 <div class="box">    
 2     <div class="center-box3">
 3         <p>【第三种方法】使用css3样式属性transform,transform中translate偏移的百分比值是相对于自身大小的</p>
 4     </div>
 5 </div>
 6 
 7 .box {
 8     background: #6c94be;
 9     width: 100%;
10     height: 450px;
11     position: relative;  
12 }
13 
14 .center-box3 {
15     position: absolute;
16     top: 50%;
17     left: 50%;
18     transform: translate(-50%,-50%);
19     background: #5B83AD;
20     width: 200px;
21 }

4.已知子元素的宽和高,设置其样式属性position:absolute;top:0;left:0;bottom:0;right:0;margin:auto;

效果图以下:

代码:

 1 <div class="box">    
 2     <div class="center-box4">
 3         <p>【第四种方法】已知宽和高,绝对定位+margin:auto;</p>
 4     </div>
 5 </div>
 6 
 7 .box {
 8     background: #6c94be;
 9     width: 100%;
10     height: 450px;
11     position: relative;
12 }
13 .center-box4 {
14     position: absolute;
15     top: 0;
16     left: 0;
17     bottom: 0;
18     right: 0;
19     width: 200px;
20     height: 200px;
21     background: #5B83AD;
22     margin: auto;
23 }
相关文章
相关标签/搜索