每天一个前端面试题之 CSS实现盒子的垂直居中
一,flex布局(不需要知道子元素的宽高)
主要是给父元素进行相应的设置
#father{
display: flex;
justify-content: center;
align-items: center;
width: 500px;
height: 500px;
border: 1px solid black;
}
#son{
width: 100px;
height: 100px;
border: 1px solid red;
}
二、定位和margin(需知道子元素的宽高)
#father{
position: relative;
width: 500px;
height: 500px;
border: 1px solid black;
}
#son{
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
width: 100px;
height: 100px;
border: 1px solid red;
}
三、定位和margin(不需要知道子元素的宽高)
#father{
position: relative;
width: 500px;
height: 500px;
border: 1px solid black;
}
#son{
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
width: 100px;
height: 100px;
border: 1px solid red;
}
四、定位和transform(不需要知道子元素的宽高)
#father{
position: relative;
width: 500px;
height: 500px;
border: 1px solid black;
}
#son{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 100px;
height: 100px;
border: 1px solid red;
}
五、display: table-cell(不需要知道子元素的宽高)
#father{
display: table-cell;
text-align: center;
vertical-align: middle;
width: 500px;
height: 500px;
border: 1px solid black;
}
#son{
display: inline-block;
width: 100px;
height: 100px;
border: 1px solid red;
}
六、grid布局(不需要知道子元素的宽高)
#father{
display: grid;
width: 500px;
height: 500px;
border: 1px solid black;
}
#son{
align-self: center;
justify-self: center;
width: 100px;
height: 100px;
border: 1px solid red;
}