132 字
1 分钟
div水平垂直居中的方法
方法一 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; }
Preview: