让一个子盒子在父盒子中水平垂直居中的方法
1.利用定位(子绝父相)
<style>
.parent {
width: 500px;
height: 500px;
border: 1px solid #000;
position: relative;
}
.child {
width: 100px;
height: 100px;
border: 1px solid #999;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
</style>
<div class="parent">
<div class="child">我是子元素</div>
</div>
通过子绝父相left:50% top:50%让子盒子定到接近父盒子中心的位置,再通过上外边距和左外边距负的子盒子自身宽高一半的距离就可以让子盒子在父盒子中水平垂直居中(这里要注意,定位用了left和top后外边距只能使用left和top 用right和bottom无效)
2.先定位再利用transform
<style>
.parent {
width: 500px;
height: 500px;
border: 1px solid #000;
position: relative;
}
.child {
width: 100px;
height: 100px;
border: 1px solid #999;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
<div class="parent">
<div class="child">我是子元素</div>
</div>
第二种方法一开始定位跟第一种方法一样,不同的地方在于用平移transform(-50%,-50%),让子盒子向左和向上平移自身宽和高的一半(这种方法与第一种方法大体上相似,不同点也是优点在于不需要去计算子盒子宽高的一半,两个50%就是指子盒子宽高的一半)
3.先定位再利用margin:auto;
<style>
.parent {
width: 500px;
height: 500px;
border: 1px solid #000;
position: relative;
}
.child {
width: 100px;
height: 100px;
border: 1px solid #999;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
</style>
<div class="parent">
<div class="child">我是子元素</div>
</div>
这种方法也是先子绝父相定位,再给子盒子上下左右全为0,再使用margin:auto;就可以让子盒子在父盒子中水平垂直居中
4.利用flex布局
<style>
.parent {
width: 500px;
height: 500px;
border: 1px solid #000;
display: flex;
justify-content: center;
align-items: center;
}
.child {
width: 100px;
height: 100px;
border: 1px solid #999;
}
</style>
<div class="parent">
<div class="child">我是子元素</div>
</div>
让父盒子变成flex弹性盒子,再给父盒子加样式 justify-content: center;(水平居中) align-items: center;(垂直居中),就可以实现子盒子水平垂直居中
5.利用display:table-cell
<style>
.parent {
width: 500px;
height: 500px;
border: 1px solid #000;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child {
width: 100px;
height: 100px;
border: 1px solid #999;
display: inline-block;
}
</style>
<div class="parent">
<div class="child">我是子元素</div>
</div>
display:table-cell;会使元素表现的类似一个表格中的单元格td,利用这个特性加样式vertical-align: middle; text-align: center;可以实现子盒子水平垂直居中