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

}

效果图如下:

相关推荐
lgbisha22 分钟前
银河麒麟入门:日志刷满终端,用 less 定位关键词并看前后几行
java·前端·less·银河麒麟
w-w0w-w1 小时前
CSRF 与 JWT 漏洞原理、攻击手法及防御机制
前端·网络·csrf
默 语1 小时前
HarmonyOS7 组件通用事件(一):四大事件总览——组件的生死、身位与存在感
服务器·前端·javascript
低代码布道师1 小时前
第06篇:用户新增——React Hook Form + Zod 搭建可复用的表单体系
前端·react.js·前端框架
前端的日常2 小时前
不花一分钱,每天白嫖 Cloudflare 的大模型接口,手把手教你接入
前端
海是岛思念的泪2 小时前
给电脑端喝水提醒工具做离线缓存:Service Worker 分层策略实战(附完整代码)
前端
牧艺2 小时前
滚动监听可以退休了:CSS Scroll-driven Animations 从原理到可上线
前端
青莲8432 小时前
SPI、AutoService、KSP、ASM:编译时与运行时各做哪一步
前端·app
打工仔折腾 AI2 小时前
智能体开发实战:Agent架构拆解与ReAct执行循环工程落地
前端·后端·python·react.js·架构·langchain·ai agent 实战
htzyl2062 小时前
升级到 TypeScript 7:哪些 tsconfig 选项会直接报错
前端·typescript