<div class="parent">
<div class="child"></div>
</div>
非定寬高情況
1. 利用絕對定位
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
2. CSS3 彈性佈局
.parent {
display: flex;
/* 定義項目在主軸上如何對齊 */
justify-content: center;
/* 定義項目在交叉軸上如何對齊 */
align-items: center;
}
// or
.parent {
display:flex;
}
.child {
margin: auto;
}
3. CSS3 transform translate 平移
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
/* 往上(x軸),左(y軸)移動自身長寬的 50% */
transform: translate(-50%, -50%);
}
4. CSS3 Grid 佈局
.parent {
display: grid;
}
.child {
justify-self: center;
align-self: center;
}
// or
.parent {
display:grid;
}
.child {
margin: auto;
}
5. vertical-align
.parent {
font-size: 0;
text-align: center;
}
.parent::before {
content: "";
display: inline-block;
width: 0;
height: 100%;
vertical-align: middle;
}
.child {
display: inline-block;
vertical-align: middle;
}
6. display:table-cell
.parent {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child {
display: inline-block;
}
固定寬高情況
1. 絕對定位+margin
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
margin-left: -40px;
margin-top: -40px;
width: 80px;
height: 80px;
}
// or
.parent {
position: relative;
}
.child {
position: absolute;
top: calc(50% - 40px);
left: calc(50% - 40px);
width: 80px;
height: 80px;
}
2. line-height + vertical-align
.parent {
height: 200px;
line-height: 200px;
text-align: center;
}
.child {
display: inline-block;
vertical-align: middle;
}