CSS之居中佈局

QHan發表於2018-12-18

在前端開發中,我們經常會遇到各種上不同場景的關於居中的佈局,一般水平居中是相對簡單,而 垂直居中與水平垂直則相應要麻煩些。在下來我們對各種場景一一列出解決方案。

水平居中

水平居中相對於其它幾中居中排列要簡單的多,按標籤元素可分為行內元素與塊級元素居中:

1、行內元素

如:a img span em b small 此類標籤元素及文字

    .center { text-align: center; }
複製程式碼

2、塊級元素

如:div section header p此類標籤元素,需要設定寬度

    .center { margin: 0 auto; }
複製程式碼

垂直居中

1、line-height

針對有且僅有一行內容時可行。將line-height值設為相對應高度即可。

2、vertical-align

針對行內元素如img span等元素,其對齊相對於文字基線。達不到完美的垂直居中,不常用。

3、其它

關於垂直居中其它方式參考水平垂直居中。


水平垂直居中

在水平垂直居中的場景中,可分為定寬定高、不定寬不定高,按不同應用場景可分如下幾種方式,在佈局中實際情況而定。

1、Flex方式

適用場景:IE9+、現代瀏覽器、響應式、不定寬不定高

<section class="center">
    <div>水平垂直居中</div>
</section>
複製程式碼
.center {
    display: flex;
    justify-content: center;
    align-items: center;
}
複製程式碼

2、絕對定位方式

適用場景:IE8+、及現代瀏覽器、響應式

<section class="center">
    水平垂直居中
</section>
複製程式碼
.center {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}
複製程式碼

3、絕對定位+transform方式

適用場景:IE9+、及現代瀏覽器、響應式、不定寬不定高

<section class="center">
    水平垂直居中
</section>
複製程式碼
.center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%)
}
複製程式碼

4、絕對定位+calc函式

適用場景:IE9+、及現代瀏覽器、定寬定高

<section class="center">
    水平垂直居中
</section>
複製程式碼
.center {
  width: 200px;
  height: 200px;
  position: absolute;
  top: calc(50% - 100px);
  left: calc(50% - 100px);
  
   
}
複製程式碼

5、絕對定位+margin負屬性

適用場景:IE6+、及現代瀏覽器、定寬定高

<section class="center">
    水平垂直居中
</section>
複製程式碼
.center {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 200px;
    height: 200px;
    margin-left: -100px;
    margin-top: -100px;
}
複製程式碼

6、Table-cell方式

適用場景:IE8+、及現代瀏覽器、不定寬不定高

<div class="table">
  <div class="table-cell">
    <div class="center-content">
      水垂直居中
    </div>
  </div>
</div>
複製程式碼
.table{ display: table; }
.table-cell {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
.center-content{
  width: 50%;
  margin: 0 auto;
}
複製程式碼

相關文章