当前位置:首页 > 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 属性快速实现水平和垂直居中。

vue实现div居中

<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%) 实现精准居中。

vue实现div居中

<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>

标签: vuediv
分享给朋友:

相关文章

vue自己实现下拉导航

vue自己实现下拉导航

实现下拉导航的基本思路 在Vue中实现下拉导航,可以通过结合Vue的响应式数据和事件绑定特性来完成。主要思路是利用v-show或v-if控制下拉菜单的显示与隐藏,并通过鼠标事件或点击事件触发状态变化。…

vue实现路由

vue实现路由

Vue 路由的实现方法 Vue 路由可以通过 Vue Router 库来实现,Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue Router 通…

实现vue table

实现vue table

Vue 表格实现方法 基础表格实现 使用 Vue 的 v-for 指令可以快速渲染表格数据。在模板中定义表格结构,通过数据绑定动态生成行和列。 <template> <tabl…

vue多选实现

vue多选实现

Vue 多选实现方法 基础实现(v-model + multiple) 在 Vue 中实现多选可以通过 <select> 元素的 multiple 属性结合 v-model 完成。v-mo…

vue环境实现

vue环境实现

Vue 环境搭建 安装 Node.js 和 npm Node.js 是运行 Vue 的基础环境,npm 是包管理工具。从 Node.js 官网 下载并安装最新稳定版本。安装完成后,在终端运行以下命令验…

vue实现通讯

vue实现通讯

Vue 组件通讯方法 父子组件通讯 父组件向子组件传递数据通过 props,子组件向父组件传递数据通过 $emit 事件。 父组件模板: <child-component :message=…