vue实现div居中
使用 Flex 布局实现居中
在父容器上设置 display: 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 实现居中
通过 position: absolute 结合 transform: translate(-50%, -50%) 实现精准居中。
<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: 0 auto 实现水平居中。
<template>
<div class="parent">
<div class="child">水平居中内容</div>
</div>
</template>
<style>
.parent {
height: 100vh;
}
.child {
width: 200px;
height: 100px;
margin: 0 auto;
background: #eee;
}
</style>
使用文本居中实现简单内容居中
通过 text-align: center 和 line-height 实现单行文本或行内元素的居中。
<template>
<div class="parent">
<div class="child">单行文本居中</div>
</div>
</template>
<style>
.parent {
height: 100vh;
text-align: center;
line-height: 100vh;
}
.child {
display: inline-block;
background: #eee;
}
</style>






