1.利用定位 (父元素相对定位,子元素绝对定位,用transform实现)
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.parent {
height: 500px;
width: 500px;
background-color: gray;
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
height: 200px;
width: 200px;
background-color: red;
color: white;
}
</style>
<body>
<div class="parent">
<div class="child">我是居中的子盒子</div>
</div>
</body>
2. 利用 flex布局 直接麻烦父盒子
.parent {
height: 500px;
width: 500px;
background-color: gray;
display: flex;
justify-content: center;
align-items: center;
}
.child {
height: 200px;
width: 200px;
background-color: red;
color: white;
}
3. 利用margin:auto;
.parent {
height: 500px;
width: 500px;
background-color: gray;
position: relative;
}
.child {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
height: 200px;
width: 200px;
background-color: red;
color: white;
}
4. 利用 display:table-cell
.parent {
height: 500px;
width: 500px;
background-color: gray;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child {
display: inline-block;
height: 200px;
width: 200px;
background-color: red;
color: white;
}
5.margin属性居中
.parent {
width: 500px;
height: 500px;
margin:auto;
overflow: hidden;
background-color: #000;
}
.child {
width: 100px;
height: 100px;
background-color: red;
margin: 150px auto 0;
}