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

}

效果图如下:

相关推荐
北海-cherish5 小时前
vue中的 watchEffect、watchAsyncEffect、watchPostEffect的区别
前端·javascript·vue.js
2501_915909066 小时前
HTML5 与 HTTPS,页面能力、必要性、常见问题与实战排查
前端·ios·小程序·https·uni-app·iphone·html5
white-persist7 小时前
Python实例方法与Python类的构造方法全解析
开发语言·前端·python·原型模式
新中地GIS开发老师7 小时前
Cesium 军事标绘入门:用 Cesium-Plot-JS 快速实现标绘功能
前端·javascript·arcgis·cesium·gis开发·地理信息科学
Superxpang7 小时前
前端性能优化
前端·javascript·vue.js·性能优化
左手吻左脸。7 小时前
解决el-select因为弹出层层级问题,不展示下拉选
javascript·vue.js·elementui
左手吻左脸。7 小时前
Element UI表格中根据数值动态设置字体颜色
vue.js·ui·elementui
李白的故乡7 小时前
el-tree-select名字
javascript·vue.js·ecmascript
Rysxt_7 小时前
Element Plus 入门教程:从零开始构建 Vue 3 界面
前端·javascript·vue.js
隐含7 小时前
对于el-table中自定义表头中添加el-popover会弹出两个的解决方案,分别针对固定列和非固定列来隐藏最后一个浮框。
前端·javascript·vue.js