132 字
1 分钟
div水平垂直居中的方法
2022-04-08

方法一 Flex 布局#

.son {
background-color: red;
width: 100px;
height: 100px;
}
.father {
width: 500px;
height: 500px;
background-color: skyblue;
display: flex;
justify-content: center;
align-items: center;
}

方法二 子绝父相 +transform: translate(-50%,-50%)#

.father {
background-color: skyblue;
width: 500px;
height: 500px;
position: relative;
}
.son {
background-color: red;
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

方法三 子绝父相 + margin:auto#

.father {
background-color: skyblue;
width: 500px;
height: 500px;
position: relative;
}
.son {
background-color: red;
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}

方法四 table 布局#

.father {
width: 300px;
padding: 100px;
vertical-align: middle;
display: table-cell;
background-color: pink;
}
.son {
height: 100px;
background-color: skyblue;
}
div水平垂直居中的方法
https://blog.oceanh.top/posts/frontend/div水平垂直居中的多种方式/
作者
Ocean Han
发布于
2022-04-08
许可协议
CC BY-NC-SA 4.0
最后修改时间
2026-01-11 15:01:45