当前位置:首页 > 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 实现单行文本或行内元素的居中。

vue实现div居中

<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-model 指令实现,其核心是结合了数据劫持(Object.defineProperty 或 Proxy)和发布-订阅模式。 数据…

vue实现展开与收起

vue实现展开与收起

Vue 实现展开与收起功能 在 Vue 中实现展开与收起功能可以通过多种方式完成,以下是一些常见的方法: 使用 v-show 或 v-if 控制显示 通过 Vue 的指令 v-show 或 v-if…

vue实现a

vue实现a

Vue 实现 A 功能的方法 在 Vue 中实现 A 功能可以通过多种方式,具体取决于 A 功能的具体需求。以下是几种常见的实现方法: 使用 Vue 组件 通过创建自定义组件来实现 A 功能。组件可…

vue实现表白

vue实现表白

Vue 实现表白页面 使用 Vue 可以快速创建一个动态、交互式的表白页面。以下是一个简单的实现方案: 基础结构 创建一个 Vue 项目或单文件组件,包含以下核心部分: <template&…

vue实现popper

vue实现popper

Vue 实现 Popper 的方法 使用 Tippy.js 库 Tippy.js 是一个轻量级的 Popper.js 封装库,提供丰富的工具提示功能。安装 Tippy.js 及其 Vue 封装: n…

vue弹幕实现

vue弹幕实现

Vue弹幕实现方法 弹幕功能常见于视频直播或评论区,以下是基于Vue的实现方案,涵盖基础弹幕、动画控制及性能优化。 基础弹幕渲染 通过v-for动态渲染弹幕列表,结合CSS实现横向移动效果。…