用CSS/CSS3 實現 水平居中和垂直居中的完整攻略


水平居中:行內元素解決方案

只需要把行內元素包裹在一個屬性display為block的父層元素中,並且把父層元素添加如下屬性即可:

 
.parent { text-align:center; } 

水平居中:塊狀元素解決方案

 
.item { /* 這里可以設置頂端外邊距 */ margin: 10px auto; } 

水平居中:多個塊狀元素解決方案
將元素的display屬性設置為inline-block,並且把父元素的text-align屬性設置為center即可:

 
.parent { text-align:center; } 

水平居中:多個塊狀元素解決方案 (使用flexbox布局實現)
使用flexbox布局,只需要把待處理的塊狀元素的父元素添加屬性display:flex及justify-content:center即可:

 
.parent { display:flex; justify-content:center; } 

垂直居中:單行的行內元素解決方案

.parent { background: #222; height: 200px; } /* 以下代碼中,將a元素的height和line-height設置的和父元素一樣高度即可實現垂直居中 */ a { height: 200px; line-height:200px; color: #FFF; } 

垂直居中:多行的行內元素解決方案
組合使用display:table-cell和vertical-align:middle屬性來定義需要居中的元素的父容器元素生成效果,如下:

.parent { background: #222; width: 300px; height: 300px; /* 以下屬性垂直居中 */ display: table-cell; vertical-align:middle; } 

垂直居中:已知高度的塊狀元素解決方案

 
.item{ top: 50%; margin-top: -50px; /* margin-top值為自身高度的一半 */ position: absolute; padding:0; } 

水平垂直居中:已知高度和寬度的元素解決方案1
這是一種不常見的居中方法,可自適應,比方案2更智能,如下:

.item{ position: absolute; margin:auto; left:0; top:0; right:0; bottom:0; } 

水平垂直居中:已知高度和寬度的元素解決方案2

.item{ position: absolute; top: 50%; left: 50%; margin-top: -75px; /* 設置margin-left / margin-top 為自身高度的一半 */ margin-left: -75px; } 

水平垂直居中:未知高度和寬度元素解決方案

.item{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); /* 使用css3的transform來實現 */ } 

水平垂直居中:使用flex布局實現

.parent{ display: flex; justify-content:center; align-items: center; /* 注意這里需要設置高度來查看垂直居中效果 */ background: #AAA; height: 300px; }


免責聲明!

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



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