HTML
<div className="parent">
<div className="child"></div>
</div>
Css
1. 元素具有固定的寬高
1.1 使用絕對定位和負邊距
.parent {
position: relative;
.child {
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
}
1.2 絕對定位和margin: 無需知道元素的寬高
.parent {
position: relative;
.child {
width: 50px;
height: 50px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
}
2. 未知高度和寬度的元素
2.1 元素為inline 或者inline-block 屬性
.parent {
display: table-cell;
vertical-align: middle;
text-align: center;
.child {
display: inline-block;
}
}
2.2 Css 3 的transform屬性
translate:設(shè)置元素在X軸,Y軸上正方向的平移變換
.parent {
position: relative;
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); // 相對自己往左往上平移50%的距離
}
}
2.3 flex 布局
.parent {
display: flex;
display: -webkit-flex; //Safari仍舊需要使用特定的瀏覽器前綴
flex-direction: row;
align-items: center;
justify-content: center;
}
或者
.parent {
display: flex;
.child {
margin: 0;
}
}
2.4 Gird 布局
但是Grid 更適合在兩個維度(包括行和列)中創(chuàng)建整個柵格化布局
.parent {
display: grid;
.child {
justify-self: center;
align-self: center;
}
}
2.5 偽元素輔助布局
.parent {
text-align: center;
&::before {
content: ''
height: 100%;
display: inline-block;
vertical-align: middle;
}
.child {
display: inline-block;
vertical-align: middle;
}
}
注意
Grid 和 Flex 都有瀏覽器兼容性問題