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


本文以<div>元素為例

本文轉載

1.已知塊級元素的寬和高,使用絕對定位absolute和外邊距實現水平垂直居中。

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

(思想:先把塊級元素中的左上角定位到父元素的中心,然后再向上向左偏移本身的一半,就達到了是本身的中心居中的目的)

效果圖如下:

 

 

代碼:

 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存在兼容性問題)

父元素樣式屬性display:flex;子元素使用margin:auto。這種方式在子塊級元素寬高不確定的時候(寬高會自適應為其里面內容的寬高)依然可以使用。

效果圖如下:

代碼:

 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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM