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

}

效果图如下:

相关推荐
炽烈小老头几秒前
函数式编程范式(三)
前端·typescript
ruoyusixian12 分钟前
chrome二维码识别查插件
前端·chrome
fengfuyao98524 分钟前
一个改进的MATLAB CVA(Change Vector Analysis)变化检测程序
前端·算法·matlab
虚拟世界AI44 分钟前
Vue.js安装指南:快速搭建开发环境
vue.js·npm·node.js
yuhaiqiang1 小时前
为什么这道初中数学题击溃了所有 AI
前端·后端·面试
djk88881 小时前
支持手机屏幕的layui后台html模板
前端·html·layui
紫_龙1 小时前
最新版vue3+TypeScript开发入门到实战教程之watch详解
前端·javascript·typescript
默默学前端2 小时前
ES6模板语法与字符串处理详解
前端·ecmascript·es6
lxh01132 小时前
记忆函数 II 题解
前端·javascript
我不吃饼干2 小时前
TypeScript 类型体操练习笔记(三)
前端·typescript