当前位置:首页 > VUE

vue实现div居中

2026-02-18 21:29:27VUE

使用 Flex 布局实现居中

在父容器上设置 display: flex,并通过 justify-contentalign-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: centerline-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>

vue实现div居中

标签: vuediv
分享给朋友:

相关文章

vue实现查询替换

vue实现查询替换

Vue 实现查询替换功能 在 Vue 中实现查询替换功能,可以通过数据绑定和字符串操作方法结合实现。以下是具体实现方式: 基础实现 <template> <div>…

vue实现一个tab栏

vue实现一个tab栏

Vue 实现 Tab 栏 基础实现(选项式 API) <template> <div class="tab-container"> <div class="t…

vue实现store

vue实现store

Vue 实现 Store 在 Vue 中,可以通过 Vuex 或 Pinia 实现全局状态管理(Store)。以下是两种主流方案的实现方法。 使用 Vuex 实现 Store Vuex 是 Vue…

vue实现alert

vue实现alert

实现自定义 Alert 组件 在 Vue 中可以通过组件化方式实现自定义 Alert 弹窗。以下是基于 Vue 3 的实现示例: 组件代码 (Alert.vue) <template>…

vue实现slider

vue实现slider

Vue 实现 Slider 组件 使用 Vue 实现 Slider 组件可以通过原生开发或借助第三方库。以下是两种常见方法: 原生实现 Slider 创建一个基础的 Slider 组件,通过 v-m…

vue实现granfana

vue实现granfana

Vue 实现类似 Grafana 的仪表盘 要在 Vue 中实现类似 Grafana 的仪表盘功能,需要结合数据可视化库、状态管理和 UI 组件。以下是关键步骤和推荐工具: 数据可视化库 使用 E…