水平垂直居中,这个问题基本上每一个面试官都会问到(对于面试我的来说,当然可能是我太差)下面就写几种常见的
1. 已知父元素和子元素宽高
.parent{
width: 100px;
height: 100px;
}
.child{
width: 50px;
height: 50px;
margin: 25px auto;
}
2. 已知宽, 使用position
.parent{
width: 100px;
height: 100px;
position: relative;
border: 1px solid #ddd;
/* text-align: center; */
}
.child{
position: absolute;
width: 50px;
height: 50px;
background: #ccc;
left: 50%;
top: 50%;
margin: -25px 0 0 -25px;
}
3.元素未知宽高
.parent{
width: 100px;
height: 100px;
position: relative;
border: 1px solid #ddd;
/* text-align: center; */
}
.child{
position: absolute;
width: 50px;
height: 50px;
background: #ccc;
left: 50%;
top: 50%;
transform: tranlate(-50%, -50%);
}
4. flex布局
.parent{
width: 100px;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
border: 1px solid #ddd;
/* text-align: center; */
}
.child{
width: 50px;
height: 50px;
}
此外还有table-cell布局,但是这个并不常用。所以还是之后再说吧
这个就这样了