方法一
原理:将left right top bottom都设置为0,使绝对定位相对整个页面定位,同时margin为auto,完成上下左右外边距等分 ,最终实现绝对定位元素的水平垂直居中
<template>
<div class="box center">
</div>
</template>
<style scoped>
.box {
width: 100px;
height: 100px;
background: red;
}
.center {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
</style>
方法二
原理:设置left,top值均为50%,同时margin-left设置为绝对定位元素width的一半取负,margin-top设为其height的一半取负。
<template>
<div class="box center">
</div>
</template>
<style scoped>
.box {
width: 100px;
height: 100px;
background: red;
}
.center {
position: absolute;
left: 50%;
margin-left: -50px;
top: 50%;
margin-top: -50px;
}
</style>