实现方法
- 实现方法:
- 定位 position + 偏移值 left + margin-left 回退
- 定位 position + 偏移值 left + CSS-2d transform
- 文字居中:text-align:center; + 行内块元素
- 弹性布局: display:flex; [推荐]
实现方法:
1、添加 margin 值 auto
2、定位 position(子绝父相) + 偏移值 left + margin-left 回退 [ 需要计算,有点 麻烦 ]
3、定位 position(子绝父相) + 偏移值 left + CSS-2d transform
4、文字居中 text-align:center; + 行内块元素
5、弹性盒子布局 [ 推荐 ]
代码实现:
<div class="box">
<div class="box1"></div>
</div>
.box{
width: 500px;
height: 300px;
background-color: aquamarine;
}
.box1{
width: 200px;
height: 100px;
background-color: lightpink;
}
接下来,将使用这个例子来测试上面提到的几种实现水平居中的方法以及记录解决测试过程中出现的一些小问题…
添加margin值(外边距):margin:auto;
.box1{
width: 200px;
height: 100px;
background-color: lightpink;
margin: auto;
}
;
}
注意点:
left: 50%; 与 transform: translateX(-50%); 中的 50% 代表的意义不一样:
left: 50%; :相对于父元素box的宽度
transform: translateX(-50%); :相对于自己box1的宽度
效果图:
文字居中:text-align:center; + 行内块元素
.box{
width: 500px;
height: 300px;
background-color: aquamarine;
text-align: center;
}
.box1{
width: 200px;
height: 100px;
background-color: lightpink;
display: inline-block;
}
注意点:
如果仅使用 text-align:center; 是无法达到水平居中的效果的,为什么?
text-align:center; 需要在行内块元素上使用的,而盒子是块级元素,所以,需要将盒子转换为行内块元素 text-align:center; 才能生效。
效果图:
弹性布局: display:flex; [推荐]
.box{
width: 500px;
height: 300px;
background-color: aquamarine;
display: flex;
/*主轴-x轴:居中*/
justify-content: center;
}
.box1{
width: 200px;
height: 100px;
background-color: lightpink;
}
效果图: