已整合至 CSS【详解】居中对齐 (水平居中 、 垂直居中、水平垂直居中)_css居中对齐-CSDN博客
方法一:子绝父相
<template>
<div class="father">
<div class="son">
</div>
</div>
</template>
<style scoped>
.father {
background: red;
height: 200px;
position: relative;
}
.son {
background: green;
width: 80%;
height: 100px;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
</style>
实现原理
1. 使用子绝父相定位
2. 默认情况下,绝对定位元素的宽度表现是“包裹性”,宽度由内部尺寸决定,但对于非替换元素,当left/right或top/bottom对立方位的属性值同时存在时,元素的宽度表现为“格式化宽度/高度” ,margin、border、padding和content内容区域会自动分配水平(和垂直)空间。
方法二:display: table-cell
<template>
<div class="father">
<div class="son">
</div>
</div>
</template>
<style scoped>
.father {
background: red;
height: 200px;
width: 200px;
display: table-cell;
vertical-align: middle;
}
.son {
background: green;
width: 80%;
height: 100px;
margin: 0 auto;
}
</style>
实现原理
1. 在 display: table-cell 上使用 vertical-align: middle 实现垂直居中
2. 使用 margin: 0 auto; 实现水平居中