水平居中
行內元素(inline)
.parent{ //父級元素爲block
text-align: center;
}
塊狀元素(block)
.child{
margin: 0 auto;
}
多塊狀元素
.parent{
text-align: center;
}
.divs{
display: inline-block;
width: 100px;
height: 50px;
}
//flex佈局
.parent{
display: flex;
justify-content: center;
}
.divs{
width: 100px;
height: 50px;
}
垂直居中
行內元素
//單個(將inline元素的高度和line-height設爲一直便可)
//多個
.parent{
width: 300px;
height: 300px;
dispaly: table-cell;
vertical-align: middle;
}
塊狀元素
//已知高度(將待居中元素設置爲絕對定位,而且設置margin-top爲居中元素高度一半的負值)
.div{
width:100px;
heght:100px;
position:absolute;
top: 50%;
margin-top: -50px;
}
//未知高度(使用transform,垂直移動-50%)
.div{
width: 100pc;
top: 50%;
position: absolute;
transform: translateY(-50%);
}
水平垂直居中
已知高度和寬度(使用絕對定位,將元素的margin-left和margin-top設爲元素寬度和高度的一半負值)
.div{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
.div{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
flex佈局
.parent{
display: flex;
justify-content:center;
align-items: center;
/*父級設置高度查看效果*/
height: 300px;
}
.div{
width: 100px;
}