方法实在太多太杂了,浅记录一下垂直居中的几大方法
1.第一种是个人比较喜欢的,运用flex布局,兼容性也较强,没啥技巧,记住就完事了。
display: flex;
flex-direction: row; /*设置主轴方向为水平,即横向水平*/
align-items: center; /*设置侧轴子元素的排列方式为居中对齐*/
2.第二种比较简单,原理就是:块级元素在水平方向上具有满屏特性,表现为水平方向上占满整个父容器的宽度,所以,当水平方向上padding、border,width都是定值时,margin左右外边距设置为auto,默认会由margin左右平分剩余空间。
margin:0 auto;/*块元素水平居中*/
height:200px;
line-height:200px;/*把行高line-height和高度height设置为一样,可以实现文本元素的垂直对齐,*/
适用于文本、行内块元素、行内元素的垂直居中,块元素的垂直居中不适用
3.第三种就是定位了
给父元素设置相对定位,子元素绝对定位,即我们常说的子绝父相;
利用绝对定位将四个定位属性的值都设置为0,top: 0; left: 0;bottom: 0;right: 0;如果子级没有设置宽高,则会被拉开到和父级一样宽高,这里子元素设置了宽高,所以宽高会按照我们的设置来显示,但是实际上子级的虚拟占位已经撑满了整个父级,这时候再给它一个margin: auto它就可以上下左右都居中了。
<style>
.father {
width: 400px;
height: 100px;
background-color: black;
position: relative;
}
.son {
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
</style>
<body>
<div class="father">
<div class="son">
水平垂直居中
</div>
</div>
</body>
4.第四种也是定位,与transform结合使用
原理就是:
设置父元素为相对定位, 子元素绝对定位,
先让元素向右和向下移动父元素的50%,在向上和向右移动自身的50%,从而移动到了父元素水平垂直方向的中间位置。
<style>
.father {
width: 400px;
height: 400px;
background-color: black;
position: relative;
}
.son {
width: 100px;
height: 100px;
position: absolute;
background-color: white;
top:50%; //向下移动父元素的50%
left:50%; //移动右父元素的50%
transform:translate(-50%, -50%); //子元素向左,向上移动自身50%实现水平垂直居中
}
</style>
<body>
<div class="father">
<div class="son">
水平垂直居中
</div>
</div>
</body>
5.最后补充一个table布局吧
父元素设置:display: table-cell;
利用vertical和text-align可以让所有的行内块级元素水平垂直居中
子元素设置:display: inline-block;
<style>
.father {
width: 400px;
height: 400px;
background-color: black;
display: table-cell;//设置table-cell
vertical-align: middle;//子属性垂直居中
text-align: center;//子属性水平居中
}
.son {
width: 100px;
height: 100px;
background-color: white;
display: inline-block;//设置为行内块
}
</style>
<body>
<div class="father">
<div class="son">
水平垂直居中
</div>
</div>
</body>