CSS
垂直水平居中
参考掘金
行内元素
.parent {
width: 400px;
height: 400px;
text-align: center;
line-height: 400px;
}
css定位
.parent {
width: 400px;
height: 400px;
position: relative;
}
.son {
position: absolute;
top: 50%;
left: 50%;
/* 未知宽高,transform */
transform: translate(-50%, -50%);
/* 已知宽高,margin: auto */
width: 100px;
height: 100px;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
/* 已知宽高 */
width: 100px;
height: 100px;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
cssflex
- 通用
.parent {
width: 500px;
height: 500px;
display: flex;
align-items: center;
justify-content: center;
}
css- margin: auto
.parent {
width: 500px;
height: 500px;
display: flex;
}
.son {
margin: auto;
}
cssgrid
.parent {
width: 500px;
height: 500px;
display: grid;
}
.son {
align-self: center;
justify-self: center;
}