壹:
position (定位方式)
父盒子设置:
position : relative
子盒子设置:
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin:auto
具体代码如下
<template>
<div class="bigBox">
<div class="smallBox"></div>
</div>
</template>
<script>
export default {
}
</script>
<style lang="scss" scoped>
.bigBox {
margin: 0 auto;
width: 600px;
height: 600px;
border: 2px solid red;
position: relative;
.smallBox {
width: 200px;
height: 200px;
border: 2px solid skyblue;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
}
</style>
贰:
position(定位) + margin 负值
先用定位 top: 50%, left: 50%, 然后利用marin负值来移动子盒子的位置,将子盒子的自身的宽高剪掉一半(50%: 200的话就-100px)
代码如下
<template>
<div class="bigBox">
<div class="smallBox"></div>
</div>
</template>
<script>
export default {
}
</script>
<style lang="scss" scoped>
.bigBox {
margin: 0 auto;
width: 600px;
height: 600px;
border: 2px solid red;
position: relative;
.smallBox {
width: 200px;
height: 200px;
border: 2px solid skyblue;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
}
</style>
叁:
position (定位) + css3 transform (位移属性)
与margin 负值 异曲同工
代码如下
<template>
<div class="bigBox">
<div class="smallBox"></div>
</div>
</template>
<script>
export default {
}
</script>
<style lang="scss" scoped>
.bigBox {
margin: 0 auto;
width: 600px;
height: 600px;
border: 2px solid red;
position: relative;
.smallBox {
width: 200px;
height: 200px;
border: 2px solid skyblue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
}
</style>
肆:
css属性 display: table-cell , vertical-align: middle
<template>
<div class="bigBox">
<div class="smallBox"></div>
</div>
</template>
<script>
export default {
}
</script>
<style lang="scss" scoped>
.bigBox {
width: 600px;
height: 600px;
border: 2px solid red;
display: table-cell;
vertical-align: middle;
.smallBox {
width: 200px;
height: 200px;
border: 2px solid skyblue;
margin: auto;
}
}
</style>
伍:
弹性布局 : display:flex
父盒子设置:
justify-content: center
align-item: center
<template>
<div class="bigBox">
<div class="smallBox"></div>
</div>
</template>
<script>
export default {
}
</script>
<style lang="scss" scoped>
.bigBox {
margin: 0 auto;
width: 600px;
height: 600px;
border: 2px solid red;
display: flex;
justify-content: center;
align-items: center;
.smallBox {
width: 200px;
height: 200px;
border: 2px solid skyblue;
}
}
</style>