在面试中,经常被问如何实现 垂直居中对齐,今天我就把我总结的一些实现方式呈现出来
在我看来,总共有3类方式:
1.转换为行内块元素,然后利用行内元素的一些居中方式来实现,比如line-height,vertical
2.利用postion:absolute | fixed 脱离文档流,然后top,left为50%, 然后王左上方向再移动自身的宽高的50%
3.利用display:flex | table-cell 等
注:下面的实现都只是看代码实现效果,忽略兼容方面的问题
首先 基本结构为:
<style>
.testCenter {
position: relative;
width: 300px;
height: 300px;
background: #ccc;
text-align:center;
}
</style>
<body>
<div class="testCenter">
<p>this is test txt...</p>
</div>
</body>
效果图为:
在横方向的居中方式很简单,如果是行内元素 就可以用 text-align:center;
如果是块元素的话,就可以用margin:0 auto 并确定width的值; 对这个为什么能居中,需要说明一下,
根据规范,父节点的content的width=(字节点的) margin(两边)+border(两边)+ padding(两边)+contentWidth,
如果margin的值为auto 那么久均匀分配给两边,这样根据公式算下来,那就实现了居中效果了
一 转换为行内块元素
1) 我们可以利用line-height的高度 等于 height的高度 的方式 来居中对齐
.testCenter :nth-child(n) {
display:inline-block;
height:120px;
line-height:120px;
}
2) 我们可以利用 vertical:middle 以及伪元素:after的方式来实现
.testCenter :nth-child(n) {
display:inline-block;
vertical-align: middle;
}
.testCenter:after {
content:"";
display:inline-block;
height: 100%;
vertical-align: middle;
}
二 利用position:absolute | fixed
1) 利用translate
.testCenter :nth-child(n) {
position: absolute;
top:50%;
left: 50%;
transform: translate(-50%,-50%);
}
2) 利用 margin负值
.testCenter :nth-child(n) {
position: absolute;
top:50%;
left: 50%;
margin:-10.5px 0 0 -57px;
}
3) 利用 定位属性都为0 margin auto 定宽高的方式
.testCenter :nth-child(n) {
position: absolute;
width:114px;
height:21px;
top:0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
三 利用设置父节点的display属性的方式
1) 设置为flex
.testCenter {
position: relative;
width: 300px;
height: 120px;
background: #ccc;
display: flex;
justify-content: center;
align-items: center;
}
2) 设置为table-cell
.testCenter {
position:relative;
width:300px;
height:120px;
background:#ccc;
display:table-cell;
vertical:middle;
text-algin:center;
}
以上,就是我知道的一些垂直居中对齐的实现方式了,如果还有其他的 欢迎补充