平常前端開發(fā)的時候經(jīng)常遇到這樣的問題,時不時就會忘記壁查,今天就想一次性把所有 CSS居中 的方法進(jìn)行總結(jié)觉至,當(dāng)做自己的備忘錄
一、水平居中
概括:
- 內(nèi)聯(lián)元素
text-v
- 塊級元素
margin: 0px auto;
- 多塊級元素睡腿,將塊級元素設(shè)置為
inline-block
,再通過text-align
- flex 布局
justify-content: center
二语御、垂直居中
概括:
1.單行元素:height
和 line-height
設(shè)置一樣的高度
- table 布局,父元素設(shè)置
display: table
席怪,子元素設(shè)置display: table-cell; vertical-align: center
- flex 布局
align-center:center
- CSS3 transform 屬性应闯,結(jié)合絕對位置,實(shí)現(xiàn)垂直居中,部分瀏覽器會有兼容性問題
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
三、水平+垂直 布局
- flex 雙重屬性設(shè)置居中
- table + 設(shè)置寬度+ margin 來完成(兼容性有較好的的保證)
- 未知寬高元素剂习,通過 transform + absolute
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
- 固定寬高——通過設(shè)置
absolute
和margin
反向設(shè)置進(jìn)行 - grid 布局(不清楚后期補(bǔ))
以下是上方部分的詳細(xì)例子
二嘀粱、垂直居中
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>
通過 height
line-height
配合進(jìn)行垂直居中
line-height
屬性設(shè)置行間的距離(不允許為負(fù)值)
這個距離是兩行之間基線的舉例猫胁,看下圖會很清楚
定義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 自動進(jìn)行調(diào)節(jié)
更詳細(xì)的例子在這里查看 深入了解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>
3. Flex 布局
通過設(shè)置 flex 布局的交叉軸方向即可 align-items: center
<style>
.flexStyle{
display: flex;
align-items: center;
height: 100px;
background-color: gray;
}
</style>
<template>
<div class="flexStyle">
flex 布局
</div>
</template>
三回懦、水平垂直居中
1. 未知寬高元素水平垂直居中
利用 2D 變換
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
利用 flex 布局
設(shè)置 主軸方向 justify-content
和 交叉軸方向 align-center
(也就是縱軸)為 center
就可以達(dá)到居中
table布局
結(jié)合開始 table
垂直居中态贤,外層設(shè)置 display:table
舱呻,內(nèi)層設(shè)置 display: table-cell;vertical: center
,最后在通過水平垂直的方法完成
引用參考
CSS line-height概念與舉例
深入了解css的行高Line Height屬性
這15種CSS居中的方式悠汽,你都用過哪幾種狮荔?