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

}

效果图如下:

相关推荐
武昌库里写JAVA5 分钟前
C语言 #pragma once - C语言零基础入门教程
vue.js·spring boot·sql·layui·课程设计
iCoding9111 分钟前
前端分页 vs 后端分页:技术选型
前端·后端·系统架构
mingtianyihou3317 分钟前
使用 Service Worker 限制请求并发数
前端
张可爱19 分钟前
20251017-Vue2八股文整理(上篇)
前端
FanetheDivine21 分钟前
ts中如何描述一个复杂函数的类型
前端·typescript
lightgis30 分钟前
chrome中的axure插件提示无法不受支持
前端·chrome
速易达网络41 分钟前
Vue3 原生移动应用开发来了
前端·javascript·css
GISer_Jing44 分钟前
LLM对话框项目技术栈&重难点总结
前端·ai·node.js
我爱学习_zwj1 小时前
【鸿蒙进阶-7】鸿蒙与web混合开发
前端·华为·harmonyos
小谭鸡米花1 小时前
高德地图电子围栏/地图选区/地图打点
前端·javascript·vue.js