CSS实现元素水平垂直居中几种方案

方案一:利用 display: inline-block; vertical-align: middle;

<div class="box">

<div></div>

<span></span>

</div>

.box {

width: 500px;

height: 500px;

background-color: red;

text-align: center;

}

.box div {

width: 200px;

height: 200px;

background-color: orange;

display: inline-block;

vertical-align: middle;

}

.box span {

width: 0;

height: 100%;

display: inline-block;

vertical-align: middle;

}

方案二:定位法(1)

<div class="box">

<div></div>

</div>

.box {

width: 500px;

height: 500px;

background-color: red;

position: relative;

}

.box div {

width: 200px;

height: 200px;

background-color: orange;

position: absolute;

top: 0;

bottom: 0;

left: 0;

right: 0;

margin: auto;

}

方案三:定位法(2)

<div class="box">

<div></div>

</div>

.box {

width: 500px;

height: 500px;

background-color: red;

position: relative;

}

.box div {

width: 200px;

height: 200px;

background-color: orange;

position: absolute;

left: 50%;

top: 50%;

margin-left: -100px;

margin-top: -100px;

}

方案四: 弹性布局

<div class="box">

<div></div>

</div>

.box {

width: 500px;

height: 500px;

background-color: red;

display: flex;

justify-content: center;

align-items: center;

}

.box div {

width: 200px;

height: 200px;

background-color: orange;

}

方案五:利用 display: table-cell; vertical-align: middle;

<div class="box">

<div></div>

</div>

.box {

width: 500px;

height: 500px;

background-color: red;

display: table-cell;

vertical-align: middle;

text-align: center;

}

.box div {

width: 200px;

height: 200px;

background-color: orange;

display: inline-block;

}

方案六:利用translate位移

<div class="box">

<div></div>

</div>

.box {

width: 500px;

height: 500px;

background-color: red;

position: relative;

}

.box div {

width: 200px;

height: 200px;

background-color: orange;

position: absolute;

top: 50%;

left: 50%;

transform: translate(-50%,-50%);

}

效果图如下:

相关推荐
smilejingwei17 分钟前
用 AI 编程生成 ECharts 图表并嵌入报表的实践
前端·人工智能·echarts·bi·报表工具·商业智能
丷丩18 分钟前
第3篇:技术拆解|3dtubetilecreater 前后端架构全解析(Vue+Express+PostGIS)
vue.js·3d·架构
Linux运维技术栈40 分钟前
Cloudflare Argo Smart Routing全球加速:优化跨境回源链路,提升跨区域访问体验
大数据·前端·数据库
恋猫de小郭1 小时前
Android CLI ,谷歌为 Android 开发者专研的 AI Agent,提速三倍
android·前端·flutter
freewlt1 小时前
从 0 搭建现代前端组件库:2026年完整实战指南
前端
凌冰_1 小时前
Thymeleaf 核心语法详解
java·前端·javascript
AIBox3651 小时前
claude 镜像 api 使用指南(2026 年4 月更新)
java·服务器·前端·人工智能·gpt·前端框架
SuperEugene1 小时前
Vue3 配置文件管理:按模块拆分配置,提升配置可维护性|配置驱动开发实战篇
前端·javascript·vue.js·驱动开发
阿凤212 小时前
后端返回文件二进制流
开发语言·前端·javascript·uniapp
落魄江湖行2 小时前
进阶篇四 Nuxt4 Server Routes:写后端 API
前端·vue.js·typescript·nuxt4