元素示例
<template>
<div class="margin"
style=" 500px;
height: 500px;
background-color: yellow">
<div class="center"
style=" 200px;
height: 200px;
background-color: red">
</div>
</div>
</template>
Part.1 绝对定位 + 百分比
.margin {
position: relative;
}
.center {
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
Part.2 绝对定位 + transform
.margin {
position: relative
}
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)
}
Part.3 绝对定位 + 0
.margin {
position: relative
}
.center {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto
}
Part.4 flex
.margin {
display: flex;
justify-content: center;
align-items: center;
}
Part.5 flex + margin
.margin {
display: flex
}
.center {
margin: auto
}