今天遇着了,就顺便把知道的让元素水平垂直居中的方法总结记录一下,免得忘了。代码结构如下:
<div class="parent">
<div class="son"></div>
</div>
1. absolute + transform
.parent{
width: 600px;
height: 400px;
border: 1px solid black;
position: relative;
}
.son{
width: 200px;
height: 100px;
border: 1px solid red;
position: absolute;
top: 50%;
left:50%;
transform: translate(-50%,-50%);
}
2. inline-block + text-align + table-cell + vertical-align
.parent{
width: 600px;
height: 400px;
border: 1px solid black;
text-align: center;
display: table-cell;
vertical-align: middle;
}
.son{
width: 200px;
height: 100px;
border: 1px solid red;
display:inline-block;
}
3. flex + justify-content + align-items
.parent{
width: 600px;
height: 400px;
border: 1px solid black;
display: flex;
justify-content: center;
align-items:center;
}
.son{
width: 200px;
height: 100px;
border: 1px solid red;
}
注:第一种和第三种都有兼容问题,但是用起来爽啊,没办法。当然我相信肯定还有其他的办法,希望广大网友多多指正。