CSS 水平/豎直居中小集合

平常前端開發(fā)的時候經(jīng)常遇到這樣的問題,時不時就會忘記,今天就想一次性把所有 CSS居中 的方法進行總結(jié),當做自己的備忘錄

一、水平居中

概括:

  1. 內(nèi)聯(lián)元素 text-v
  2. 塊級元素 margin: 0px auto;
  3. 多塊級元素,將塊級元素設置為 inline-block,再通過 text-align
  4. flex 布局 justify-content: center

二、垂直居中

概括:

1.單行元素:heightline-height 設置一樣的高度

  1. table 布局,父元素設置 display: table ,子元素設置 display: table-cell; vertical-align: center
  2. flex 布局 align-center:center
  3. CSS3 transform 屬性,結(jié)合絕對位置,實現(xiàn)垂直居中,部分瀏覽器會有兼容性問題
.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

三、水平+垂直 布局

  1. flex 雙重屬性設置居中
  2. table + 設置寬度+ margin 來完成(兼容性有較好的的保證)
  3. 未知寬高元素,通過 transform + absolute
.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
  1. 固定寬高——通過設置 absolutemargin 反向設置進行
  2. grid 布局(不清楚后期補)

以下是上方部分的詳細例子


二、垂直居中

1. 單行內(nèi)聯(lián)元素垂直居中

<style>
  .main{
    height: 200px;
    background-color: #fcc;
    overflow: hidden;
    line-height: 40px;
    font-size: 40px;
  }
</style>
<template>
  <div class="main">
      我是一行
  </div>
</template>
line-height、height 配合單行垂直居中

通過 height line-height 配合進行垂直居中

line-height 屬性設置行間的距離(不允許為負值)

這個距離是兩行之間基線的舉例,看下圖會很清楚

image.png

定義height 的五種方式:

1.line-height可以被定義為:body{line-height:normal;}

2.line-height可以被定義為:body{line-height:inherit;}

3.line-height可以使用一個百分比的值body{line-height:120%;}

4.line-height可以被定義為一個長度值(px,em等) body{line-height:25px;}

5.line-height也可以被定義為純數(shù)字, body{line-height:1.2}—————會通過font-size 自動進行調(diào)節(jié)

更詳細的例子在這里查看 深入了解css的行高Line Height屬性

2.多行垂直居中

<style>
  .table{
    display: table;
    background-color: #4cd1d4;
    height: 150px;
  }
  .cell{
    display: table-cell;
    vertical-align: middle;
  }
</style>
<template>
    <div class="table">
      <div class="cell">
        我是一行
        <br>
        我是二行
      </div>
    </div>
</template>
table 多行垂直居中

3. Flex 布局

通過設置 flex 布局的交叉軸方向即可 align-items: center

<style>
  .flexStyle{
    display: flex;
    align-items: center;
    height: 100px;
    background-color: gray;
  }
</style>
<template>
  <div class="flexStyle">
    flex 布局
  </div>
</template>
image.png

三、水平垂直居中

1. 未知寬高元素水平垂直居中

利用 2D 變換

.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

利用 flex 布局

設置 主軸方向 justify-content 和 交叉軸方向 align-center (也就是縱軸)為 center 就可以達到居中

table布局

結(jié)合開始 table 垂直居中,外層設置 display:table,內(nèi)層設置 display: table-cell;vertical: center,最后在通過水平垂直的方法完成

引用參考

CSS line-height概念與舉例
深入了解css的行高Line Height屬性
這15種CSS居中的方式,你都用過哪幾種?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容