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

}

效果图如下:

相关推荐
燕落南枝6 分钟前
CSS 字体样式:颜色、字体族、倾斜、加粗与装饰
前端·css
鬼手点金9 分钟前
消息的四种角色
java·前端·人工智能·git·深度学习
陈随易12 分钟前
副业搞钱之代办永不过时
前端·后端·程序员
古夕13 分钟前
同样的 font-weight,为什么这个项目的字体就是更细?
前端·javascript
程序员200714 分钟前
抽卡玄学?不,是数学:保底机制下出货概率到底怎么算
前端
excel15 分钟前
请求很慢,问题一定出在服务器吗?看懂浏览器网络耗时
前端·后端
卤蛋fg619 分钟前
vue 下拉树组件 vxe-table-select 实现分页多选
vue.js
代码猎人20 分钟前
前端怎么熟悉ES6+语法
前端
代码猎人22 分钟前
前端怎么精通Vue2核心原理
前端
夏天要喝冰可乐23 分钟前
我用 WorkBuddy 做了个「GitHub 考古所」:输入一个用户名,出土你的编程人格档案
前端·github