Css實現垂直居中的幾種方法

在前端佈局過程當中,咱們實現水平居中比較簡單,通常經過margin:0 auto;和父元素 text-align: center;就能實現。但要實現垂直居中就沒有那麼容易,下面向你們分享下我工做中實現垂直居中的幾種方法。javascript

一、line-height等於hieght/只設line-height

這種方法比較適合文字的居中,其核心是設置行高(line-height)等於包裹他的盒子的高,或者不設高度只設行高,這種適合文字居中且高度固定的場景,使用起來比較方便也比較有用。css

//html
<div class="middle">555</div>
 
//css
.middle{
  height: 50px;
  line-height: 50px;
  background: red;
}
複製代碼

值得注意的是若是是行內元素,由於其沒有高度,需先把行內元素轉換爲行內塊或者塊元素。

二、vertical-align: middle

這種實現元素的居中須要配合父元素設有等於自身高度的行高,且此元素是行內塊元素。 只有三個條件都具有,才能實現垂直居中。代碼以下:html

//html
<div class="main">
   <div class="middle"></div>
</div>

//css
.main {
  width: 200px;
  height: 300px;
  line-height: 300px;
  background: #dddddd;
}
.middle{
  background: red;
  width: 200px;
  height: 50px;
  display: inline-block;//或者display: inline-table;
  vertical-align: middle;
}
複製代碼

須要注意的是這種方法須要一個固定的行高,且實現的居中實際上是近似居中,並非真正意義的居中。前端

三、絕對定位加負外邊距

這種方法核心在於先設置須要居中的元素爲絕對定位,在設置其top:50%; 加上 margin-top等於負的自身高度的一半來實現居中。好處是實現起來比較方便,且父元素的高度能夠爲百分比,也不用設行高。代碼以下:java

//html
<div class="main">
  <div class="middle"></div>
</div>
  
//css
.main {
  width: 60px;
  height: 10%;
  background: #dddddd;
  position: relative;//父元素設爲相對定位
}
.middle{
  position: absolute;//設爲絕對定位
  top: 50%;//top值爲50%
  margin-top: -25%;//設margin-top爲元素高度的一半
  width: 60px;
  height: 50%;
  background: red;
}

複製代碼

四、絕對定位加margin:auto

先上代碼:瀏覽器

//html
<div class="main">
  <div class="middle"></div>
</div>
  
//css
.main {
  width: 60px;
  height: 10%;
  background: #dddddd;
  position: relative;//父元素設爲相對定位
}
.middle{
  width: 30%;
  height: 50%;
  position: absolute;//設爲絕對定位
  top: 0;
  bottom: 0;//top、bottom設0便可,
  left: 0;//若是left、right也設爲0則可實現水平垂直都居中
  right: 0;
  margin:auto;
  background: red;
}

複製代碼

這種方法好處是不止能夠實現垂直居中,還能夠實現水平居中,壞處是在網絡或性能很差的狀況下會有盒子不直接定到位的狀況,形成用戶體驗很差。網絡

五、flex佈局

flex佈局能夠很方便的實現垂直與水平居中,好處不少,在移動端使用比較普遍,壞處就是瀏覽器兼容性很差。代碼以下:佈局

//html
<div class="main">
  <div class="middle"></div>
</div>
  
//css
.main {
  width: 60px;
  height: 10%;
  background: #dddddd;
  display: flex;//設爲flex
  justify-content: center;//水平居中
  align-items: center;//垂直居中
}
.middle{
  width: 30%;
  height: 50%;
  background: red;
}

複製代碼

相關文章
相關標籤/搜索