【學習筆記】塊級元素水平垂直居中方法

本文以<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 }
相關文章
相關標籤/搜索