vue实现div居中
Vue 中实现 Div 居中的方法
使用 Flex 布局
在父容器上应用 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: #eee;
}
</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: #eee;
}
</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: #eee;
}
</style>
使用 margin: auto
对于块级元素,通过设置 margin: auto 实现水平居中,垂直居中需结合其他方法。
<template>
<div class="parent">
<div class="child">居中内容</div>
</div>
</template>
<style>
.parent {
height: 100vh;
display: flex;
}
.child {
margin: auto;
width: 200px;
height: 100px;
background: #eee;
}
</style>
使用文本居中
对于行内或行内块元素,可以通过 text-align: center 和 line-height 实现简单居中。

<template>
<div class="parent">
<span class="child">居中内容</span>
</div>
</template>
<style>
.parent {
text-align: center;
line-height: 100vh;
height: 100vh;
}
.child {
display: inline-block;
width: 200px;
height: 100px;
background: #eee;
vertical-align: middle;
}
</style>
以上方法可以根据具体需求选择,Flex 和 Grid 布局是现代开发中推荐的方式。






