参考:CSS常见布局及解决方案
把简单做好也不简单-css水平垂直居中
1、父节点:relative + 子节点:absolute + transform
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
.parent {
background-color: #0eabdf;
width: 300px;
height: 300px;
position: relative;
}
.child {
background-color: #fe6464;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
</html>
绝对定位脱离文档流,不会对后续元素的布局造成影响。
transform 为 CSS3 属性,有兼容性问题
效果图:
2. inline-block + text-align + table-cell + vertical-align
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
.parent {
background-color: #0eabdf;
width: 300px;
height: 300px;
text-align: center;
display: table-cell;
vertical-align: middle;
}
.child {
background-color: #fe6464;
display: inline-block;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
</html>
兼容性好
效果图:
3. flex + justify-content + align-items
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
.parent {
background-color: #0eabdf;
width: 300px;
height: 300px;
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /*垂直居中*/
}
.child {
background-color: #fe6464;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
</html>
只需设置父节点属性,无需设置子元素
蛋疼的兼容性问题
效果图:
4、相对与绝对定位
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.parent-div {
width: 100px;
height: 100px;
background-color: red;
position: relative;
}
.child-div {
width: 50px;
height: 50px;
background-color: #000;
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
</style>
</head>
<body>
<div class="parent-div">
<div class="child-div"></div>
</div>
</body>
</html>