實作效果
容器基礎樣式/* 容器基礎樣式 */
.box-wrap {
width: 400px;
height: 400px;
border: 1px solid #eeeeee;
margin-top: 20px;
}
.box {
width: 200px;
height: 200px;
background-color: green;
/* 文字居中 */
text-align: center;
color: #ffffff;
line-height: 200px;
}
1、flex
.box-wrap {
display: flex;
justify-content: center;
align-items: center;
}
2、table-cell
.box-wrap {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box{
display: inline-block;
}
3、margin+transform
.box {
margin: 50% auto;
transform: translateY(-50%);
}
4、inline-block + vertical-align(沒有測試通過)
.box-wrap{
/*使行内元素或者行内塊級元素水準居中*/
text-align: center;
}
.box {
display: inline-block;
vertical-align: middle;
}
5、absolute + margin
.box-wrap {
position: relative;
}
.box {
position: absolute;
left: 50%;
top: 50%;
/* 盒子高度的一半 */
margin-left: -100px;
margin-top: -100px;
}
6、absolute + margin-auto
.box-wrap {
position: relative;
}
.box {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
7、absolute + transform
.box-wrap {
position: relative;
}
.box {
position: absolute;
left: 50%;
top: 50%;
/* 移動自身的50% */
transform: translate(-50%, -50%);
}
8、grid + self
.box-wrap {
display: grid;
}
.box {
align-self: center;
justify-self: center;
}
9、grid + items
.box-wrap {
display: grid;
place-items: center;
}