1.利用定位(常用)
<body>
<div class="father">
<div class="son">我是子元素</div>
</div>
</body>
<style>
.father{
width: 500px;
height: 500px;
border: 1px solid red;
position: relative;
}
.son{
width: 100px;
height: 100px;
border: 1px solid pink;
position: absolute;
top:50%;
left:50%;
margin-top: -50px; //盒子的一半
margin-left: -50px;
}
</style>
2.利用margin:auto
<body>
<div class="father">
<div class="son">我是子元素</div>
</div>
</body>
<style>
.father{
width: 500px;
height: 500px;
border: 1px solid red;
position: relative;
}
.son{
width: 100px;
height: 100px;
border: 1px solid pink;
position:absolute;
margin: auto;
top:0;
bottom: 0;
left:0;
right: 0;
}
</style>
3.利用transform
<body>
<div class="father">
<div class="son">我是子元素</div>
</div>
</body>
<style>
.father{
width: 500px;
height: 500px;
border: 1px solid red;
position: relative;
}
.son{
width: 100px;
height: 100px;
border: 1px solid pink;
position:absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);
}
</style>
4.计算父盒子和子盒子的空间距离
<body>
<div class="father">
<div class="son">我是子元素</div>
</div>
</body>
<style>
.father{
width: 500px;
height: 500px;
border: 1px solid red;
}
.son{
width: 100px;
height: 100px;
border: 1px solid pink;
margin-top: 200px;
margin-left: 200px;
}
</style>
5.利用display:flex
<body>
<div class="father">
<div class="son">我是子元素</div>
</div>
</body>
<style>
.father{
width: 500px;
height: 500px;
border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.son{
width: 100px;
height: 100px;
border: 1px solid pink;
}
</style>
6.利用display:table-cell
<body>
<div class="father">
<div class="son">我是子元素</div>
</div>
</body>
<style>
.father{
width: 500px;
height: 500px;
border: 1px solid red;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.son{
width: 100px;
height: 100px;
border: 1px solid pink;
display: inline-block;
}
</style>
标签:居中,盒子,solid,100px,height,垂直,width,1px,border
From: https://blog.51cto.com/u_16202629/6859402