1.文本垂直居中
- 1.1.单行文本垂直居中
行高=盒子高度
div {
width: 300px;
height: 150px;
border: solid;
/*设置水平居中*/
text-align: center;
/*设置行高等于高度,可以让div中的单行文本垂直居中*/
line-height: 150px;
}
- 1.2.多行文本垂直居中
- 1.2.1.父级高度不固定
通过设置padding-top=padding-bottom
- 1.2.1.父级高度不固定
div {
width: 300px;
border: solid;
/*父级高度不固定,其高由内容撑开*/
/* 设置padding-top和padding-bottom的值一样,使之看起来垂直居中 */
padding: 50px 60px;
/*通过行高设置一下行间距,排版更美观*/
line-height: 40px;
}
- 1.2.2.父级高度固定
vertical-align:middle
div {
width: 210px;
height: 400px;
border: solid;
display: table-cell;
vertical-align: middle;
}
2.子盒子垂直居中
- 2.1.利用定位
.wrap {
width: 200px;
height: 200px;
border: solid;
position: relative;
}
.box {
width: 100px;
height: 100px;
background: pink;
position: absolute;
left: 50%;
top: 50%;
margin-top: -50px;
margin-left: -50px;
}
- 2.2.利用位移:transform:translate
/*上例的margin用transform代替(注意书写格式与正负号)*/
.box {
/* margin-top: -50px;
margin-left: -50px; */
transform: translateX(-50%) translateY(-50%);
}
- 2.3.利用绝对布局:absolute
.box {
/* left: 50%;
top: 50%; */
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
- 2.4.利用vertical-align
.wrap {
width: 200px;
height: 200px;
border: solid;
/*方法与多行文本的垂直居中相同*/
/*看这两行就够了*/
display: table-cell;
vertical-align: middle;
}
.box {
width: 100px;
height: 100px;
background: pink;
}
- 2.5.利用弹性盒子,设置父盒子主轴侧轴居中
.wrap {
width: 200px;
height: 200px;
border: solid;
display: flex;
justify-content: center;
align-items: center;
}