水平居中
方法一: 也是平常用的最基本,最多的了。
text-align: center ;
方法二:
子盒子的样式加:marign: auto ;
<div class="big-div">
<div class="small-div"></div>
</div>
<style>
.big-div{
width: 300px;
height: 300px;
background: pink;
}
.small-div{
width: 100px;
height: 100px;
background: skyblue;
margin: auto;
}
</style>
效果图:
方法三: 让盒子移动来居中
父盒子加相对定位,子盒子绝对定位
<div class="big-div">
<div class="small-div"></div>
</div>
<style>
.big-div{
position: relative;
width: 150px;
height: 150px;
background: pink;
}
.small-div{
position: absolute;
left: 50%;
transform: translateX(-50%);
width: 50px;
height: 50px;
background: skyblue;
/* margin: auto; */
}
</style>
第一步:子盒子右移50%( left: 50% ),是相对”父亲”宽度的50%,效果图:
此时明显还没有实现居水平中
第二步:子盒子继续左移自身宽度的50% ( transform: translateX(-50%) ),就是完成居中。效果图:
方法四: 弹性盒模型(flex布局)
父盒子:设置
display: flex ;
justify-content: center ;(主轴上子元素对其方式:居中)
即可。
垂直居中
方法一: 设置文字的行高的等于父盒子的高度。
line-height: 父盒子高度;
<div class="big-div">
<span>588899</span>
</div>
<style>
.big-div{
width: 150px;
height: 150px;
background: pink;
}
span{
line-height: 150px;
}
</style>
效果图:
方法二: 让盒子移动来居中
父盒子加相对定位,子盒子绝对定位
<div class="big-div">
<div class="small-div"></div>
</div>
<style>
.big-div{
position: relative;
width: 150px;
height: 150px;
background: pink;
}
.small-div{
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 50px;
height: 50px;
background: skyblue;
}
</style>
第一步:子盒子下移50%(top: 50%;),是相对”父亲”高度的50%,效果图:
此时明显还没有实现居垂直中
第二步:子盒子继续上移自身高度的50%( transform: translateY(-50%) ),就是完成居中。效果图:
方法三: 弹性盒模型(flex布局)
父盒子:设置
display: flex ;
align-items: center ;(交叉轴上子元素对其方式:居中)
即可。
水平垂直居中
方法一: 使用
text-align: center;
line-height: 父盒子高度 ;
即可。
方法二: 父盒子使用 flex 布局
display: flex;
justify-content: center;
align-items: center;