前言
在找工作的時候,面試官在問到css基礎的時候,基本上實現(xiàn)水平居中都會被問到,作為一名前端開發(fā),此最最基本的css技能怎么會難得倒我們呢!其實這個需求在平時開發(fā)的時候也會遇到,只是我們基本上都使用自己最常用的方式,其實還有其他幾種方式實現(xiàn),這些我們也應該掌握。

效果圖
準備
在html界面上,我寫了兩個div盒子,一個是類名為father的盒子,另一個是它的子盒子類名為son。如下:
<body>
<div class="father">
<div class="son">
</div>
</div>
</body>
去除一下默認的8px邊距
<style>
* {
padding: 0;
margin: 0;
}
</style>
1. 定位+負margin方式(已知子盒子大?。?/h1>
假設已知子盒子大小為200*200
- 父盒子添加定位
position: relative;
- 子盒子添加定位
position: absolute;
- 子盒子top和left都為50%
- 子盒子的
margin-top和margin-left分別設置為- 子盒子高度 / 2 和 - 子盒子寬度 / 2
假設已知子盒子大小為200*200
position: relative;
position: absolute;
margin-top和margin-left分別設置為- 子盒子高度 / 2 和 - 子盒子寬度 / 2
css樣式如下
/* 已知盒子大小
假如盒子大小為200*200
*/
.father {
position: relative;
height: 500px;
background-color: pink;
}
.son {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
margin-top: -100px;
margin-left: -100px;
background-color: purple;
}
2. 定位+margin: auto方式(已知子盒子大?。?/h1>
假設已知子盒子大小為200*200
- 父盒子添加定位
position: relative;
- 子盒子添加定位
position: absolute;
- 子盒子的
top、left、right、bottom都設置為0
- 子盒子
margin設置為auto
假設已知子盒子大小為200*200
position: relative;
position: absolute;
top、left、right、bottom都設置為0margin設置為auto
css樣式如下
/* 已知盒子大小
假如盒子大小為200*200
*/
.father {
position: relative;
height: 500px;
background-color: pink;
}
.son {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 200px;
height: 200px;
margin: auto;
background-color: purple;
}
3. 定位+transform
此方法最為常見,因為盒子的大小可以是未知的
- 父盒子添加定位
position: relative; - 子盒子添加定位
position: absolute; - 子盒子
top和left
css樣式如下
.father {
position: relative;
height: 500px;
background-color: pink;
}
.son {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: purple;
}

效果圖
4. flex-box布局實現(xiàn)
該布局也比較常用,因為簡單快捷
- 父盒子設置
display: flex;(默認方向為row,即flex-direction: row;) - 父盒子設置主軸對齊方式為center,
justify-content: center; - 父盒子設置交叉軸對齊方式為center,
align-items: center;
css樣式如下
.father {
display: flex;
/* flex-direction: row; */
justify-content: center;
align-items: center;
height: 500px;
background-color: pink;
}
.son {
background-color: purple;
}
5. flex-box + margin: auto
此方法最常用,也最簡單。給設置為flex布局,子盒子margin設置為auto。
css代碼
.father {
display: flex;
height: 500px;
background-color: pink;
}
.son {
margin: auto;
background-color: purple;
}
6. table-cell實現(xiàn)
table-cell外層需要有個table的父盒子,table-cell中的子盒子擁有行內(nèi)元素的特性
布局
<body>
<div class="father">
<div class="son">
<div class="middle">我是居中的盒子呀</div>
</div>
</div>
</body>
css樣式
.father {
display: table;
width: 100%;
height: 500px;
background-color: pink;
}
.son {
display: table-cell;
text-align: center;
vertical-align: middle;
background-color: purple;
}
.middle {
display: inline-block;
background-color: lightgreen;
}

效果圖
總結(jié)
至此,幾種水平垂直居中的css方案就介紹到這里。其中,項目中比較常用的是方案3、方案4和方案5,但是兼容性比較差,低版本的IE不太支持。可以選擇方案6進行解決~