CSS實現水平垂直居中的方式有哪些?
CSS實現水平垂直居中的方式有哪些?
基本結構樣式:
.box {
width: 400px;
height: 400px;
background-color: red;
}
.inner {
width: 100px;
height: 100px;
background-color: blue;
}
<div class="box">
<div class="inner"></div>
</div>
1.利用flex布局
將父元素啟動flex布局,並設置
justify-content: center; align-items: center;。
添加樣式:
.box {
display: flex;
justify-content: center;
align-items: center;
}
2.利用flex+margin
父元素設置
display: flex;,子元素設置margin: auto;。
添加樣式:
.box { display: flex; }
.inner { margin: auto; }
3.利用定位,子絕父相
3.1.利用margin: auto(偏移量都為0)
將子元素的top、left、right、bottom都設置為0,再設置其margin為auto即可。
添加樣式:
.box { position: relative; }
.inner {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
3.2.利用平移translate
先設置子元素的top和left都為50%,即父元素寬高的一半,再使用translate往回走自己寬高的一半。
添加樣式:
.box { position: relative; }
.inner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
4.知道具體寬高,通過計算
4.1.子絕父相,直接計算或者使用calc()
添加樣式:
.box { position: relative; }
.inner {
position: absolute;
/* 直接計算 */
/* top: 150px;
left: 150px; */
top: calc(50% - 50px);/* 使用calc() */
left: calc(50% - 50px);
}
4.2.利用margin
子元素設置
margin-top;但是存在父子共用外邊距問題,父元素需要設置overflow: hidden;。
添加樣式:
.box { overflow: hidden; }
.inner {
margin: 0 auto;
margin-top: 150px;
}
4.3.利用padding
父元素設置padding,防止父盒子被撐大,需加上
box-sizing: border-box;。
添加樣式:
.box {
box-sizing: border-box;
padding: 150px;
}
5.利用display的table-cell屬性值
5.1.利用display+vertical-align
父元素設置
display: table-cell;和vertical-align: middle;,子元素設置margin: 0 auto;。
添加樣式:
.box {
display: table-cell;
vertical-align: middle;
}
.inner { margin: 0 auto; }
5.2.利用display+vertical-align+text-align
父元素設置
display: table-cell以及內容的水平和垂直居中,注意子元素要設置為行內塊。
添加樣式:
.box {
display: table-cell; /* 此元素會作為一個表格單元格顯示 */
vertical-align: middle; /* 把此元素放置在父元素的中部 */
text-align: center;
}
.inner { display: inline-block; }
6.以上方法最終運行結果


