css的垂直居中与水平居中
一、 块级盒子水平居中
- width 必须有宽度
- 盒子的左右外边距 auto
100px;
height: 100px;
margin: 0 auto;
二、 行盒/行块盒/文字水平居中
只需要在父级元素使用 text-align: center; 即可
三、 文字垂直居中
包裹文字的盒子设置行高等于盒子高度,这样行高的上空隙和下空隙就会把文字内容挤到中间
如果行高小于盒子高度,文字会偏上,行高大于盒子高度,文字会偏下
height: 50px;
line-height: 50px;
四、绝对定位的盒子居中
加了绝对定位的盒子不能通过 margin:0 auto
实现水平居中,但可以通过以下计算方式实现水平和垂直居中
1. 绝对定位的盒子水平居中
- 让盒子的左侧移动到父级元素的水平中心位置
- 让盒子向左移动自身宽度的一半
100px;
height: 100px;
background-color: green;
position: absolute;
/*让盒子的左侧移动到父级元素的水平中心位置*/
left: 50%;
/*1. 使用margin-left: -50px;需要自己计算出盒子自身宽度的一半,如果盒子宽度改变了,这里也要改*/
/*margin-left: -50px;*/
/*2. transform: translateX(-50%);过渡,自动计算自身盒子的一半宽度*/
transform: translateX(-50%);
2. 绝对定位的盒子垂直居中
- 让盒子的上侧移动到父级元素的水平中心位置
- 让盒子向上移动自身宽度的一半
100px;
height: 100px;
background-color: green;
position: absolute;
/*让盒子的上侧移动到父级元素的垂直中心位置*/
top: 50%;
/*1. 使用margin-top: -50px;需要自己手动计算出盒子自身高度的一半,如果盒子高度改变了,这里也要改*/
/*margin-top: -50px;*/
/*2. 使用calc函数上移自身高度50%,自动计算*/
/*margin-top: calc(-$height / 2);*/
/*3. transform: translateY(-50%);移动自身盒子的一半高度*/
transform: translateY(-50%);
五、使用flex布局实现水平和垂直居中
- display: flex;使用flex容器布局
- justify-content: center;/默认情况下,flex布局容器中flex项目水平居中/
- align-items: center;flex布局容器中flex项目在交叉轴居中对齐,默认情况下是垂直居中
flex布局实现水平和垂直居中代码示例
- 创建html
<div class="one">
<div class="two"></div>
</div>
- 创建css
.one{
display: flex;
/*flex布局容器中flex项目水平居中*/
justify-content: center;
/*flex布局容器中flex项目在交叉轴居中对齐,默认情况下是垂直居中*/
align-items: center;
400px;
height: 400px;
background-color: pink;
}
.two{
200px;
height: 200px;
background-color: black;
}