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

}

效果图如下:

相关推荐
京东零售技术2 分钟前
京东小程序JS API仓颉改造实践
前端
老A技术联盟11 分钟前
从小白入门,基于Cursor开发一个前端小程序之Cursor 编程实践与案例分析
前端·小程序
风铃喵游14 分钟前
构建引擎: 打造小程序编译器
前端·小程序·架构
sunbyte19 分钟前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | ThemeClock(主题时钟)
前端·javascript·css·vue.js·前端框架·tailwindcss
小飞悟28 分钟前
🎯 什么是模块化?CommonJS 和 ES6 Modules 到底有什么区别?小白也能看懂
前端·javascript·设计
浏览器API调用工程师_Taylor28 分钟前
AOP魔法:一招实现登录弹窗的全局拦截与动态处理
前端·javascript·vue.js
FogLetter29 分钟前
初识图片懒加载:让网页像"懒人"一样聪明加载
前端·javascript
微客鸟窝31 分钟前
一文搞懂NVM管理Node.js:从安装到实战全攻略
前端
归于尽31 分钟前
Cookie、Session、JWT 的前世今生
前端
程序员辉哥32 分钟前
学会在Cursor中使用Rules生成代码后可以躺平了吗?
前端·后端