實(shí)現(xiàn)垂直居中布局
1.已知寬高
/* 1 */
.container{
width: 300px;
height: 300px;
background: yellowgreen;
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -150px;
}
/* 2 */
.container{
width: 300px;
height: 300px;
background: yellowgreen;
position: absolute;
top: calc(50% - 150px);
left: calc(50% - 150px);
}
2.未知寬高
/* 1 */
.container{
background: yellowgreen;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* 2 position + auto*/
.container{
background: yellowgreen;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
/* 3 flex+ auto */
.wrapper {
width: 100%;
height: 100vh;
display: flex;
}
.wrapper .content {
margin: auto;
}
/* 4. 父元素居中*/
.wrapper {
display: flex;
/* 盒子橫軸的對(duì)齊方式 */
justify-content: center;
/* 盒子縱軸的對(duì)齊方式 */
align-items: center;
}
/* 5.body內(nèi)部居中*/
.content {
/* 1vh = 1% * 視口高度 */
margin: 50vh auto;
transform: translateY(-50%);
}
css 盒子模型(默認(rèn)為content-box)
CSS盒模型本質(zhì)上是一個(gè)盒子,封裝周圍的HTML元素,它包括:邊距,邊框,填充,和實(shí)際內(nèi)容。
image.png
- 標(biāo)準(zhǔn)盒子模型:width = content
- IE盒子模型:width = content + pading + border
- 設(shè)置標(biāo)準(zhǔn)盒子模型:box-sizing : content-box
- 設(shè)置IE盒子模型:box-sizing : border-box
