水平垂直居中一
使用定位
div {
position: absolute;
width: 300px;
height: 300px;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: pink;
/* 方便看效果 */
}
效果
水平垂直居中二
未知容器的宽高, 利用 transform 属性
div {
position: absolute; /* 相对定位或绝对定位均可 */
width:500px;
height:300px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: pink;
}
水平垂直居中三
利用 flex 布局
.container {
display: flex;
align-items: center;
justify-content: center;
height: 500px; border:1px solid red;
}
.container div {
width: 100px;
height: 100px;
background-color: pink; /* 方便看效果 */
}