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%);

}

效果图如下:

相关推荐
UndefeatedJie32 分钟前
全栈项目架构三支柱:模块化 × RESTful × 语义化HTML,附AI辅助开发心法
html
陆枫Larry1 小时前
小程序包体积优化:用 SVG 图片替换 iconfont,并保留 CSS 控色能力
前端
凌奕1 小时前
Claude Code 上线了"一键发网页"功能:报告做完直接甩链接,部署这一步彻底消失
html·claude
环境栈笔记2 小时前
多账号浏览器选型检查清单:Profile、权限、Session 和任务日志怎么评估
前端·人工智能·后端·自动化
前端炒粉2 小时前
手写promise
java·前端·javascript
LaughingZhu2 小时前
智能体经典范式构建:ReAct、Plan-and-Solve 与 Reflection
前端·react.js·前端框架
荒诞英雄2 小时前
从 17MB Vendor 大包到按需加载:Vite 多入口 Vue 组件库首屏优化实践
vue.js·vite
jsonbro2 小时前
手把手带你实现发布订阅模式
前端·vue.js·设计模式
一只猫的梦2 小时前
自动化模块 (Automation Module)
前端·chrome
熊猫钓鱼>_>3 小时前
Electron:当 Web 技术统治桌面
大数据·前端·javascript·人工智能·架构·electron·agent