vue实现div居中
Vue 中实现 div 居中的方法
使用 Flexbox 布局
通过设置父容器为 flex 布局,并利用 justify-content 和 align-items 属性实现水平和垂直居中。
<template>
<div class="parent">
<div class="child">居中内容</div>
</div>
</template>
<style>
.parent {
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* 确保父容器有高度 */
}
.child {
width: 200px;
height: 100px;
background: #f0f0f0;
}
</style>
使用 Grid 布局
通过 CSS Grid 的 place-items 属性快速实现居中效果。

<template>
<div class="parent">
<div class="child">居中内容</div>
</div>
</template>
<style>
.parent {
display: grid;
place-items: center;
height: 100vh;
}
.child {
width: 200px;
height: 100px;
background: #f0f0f0;
}
</style>
使用绝对定位 + transform
通过绝对定位将元素定位到父容器中心,再通过 transform 微调。

<template>
<div class="parent">
<div class="child">居中内容</div>
</div>
</template>
<style>
.parent {
position: relative;
height: 100vh;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 100px;
background: #f0f0f0;
}
</style>
使用 margin: auto
适用于已知宽高的块级元素,通过设置 margin: auto 实现水平居中,结合其他方法实现垂直居中。
<template>
<div class="parent">
<div class="child">居中内容</div>
</div>
</template>
<style>
.parent {
display: flex;
height: 100vh;
}
.child {
margin: auto;
width: 200px;
height: 100px;
background: #f0f0f0;
}
</style>
使用 CSS 变量动态控制
结合 Vue 的动态样式绑定,实现更灵活的居中控制。
<template>
<div class="parent" :style="parentStyle">
<div class="child" :style="childStyle">居中内容</div>
</div>
</template>
<script>
export default {
data() {
return {
parentStyle: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh'
},
childStyle: {
width: '200px',
height: '100px',
background: '#f0f0f0'
}
};
}
};
</script>






