不固定高宽div垂直居中的方法

小白兔
25个月前

258 0

一般div的水平居中直接使用margin等方法可以轻易实现,但是不固定宽高的 div 垂直居中稍微复杂一些。

方法一:伪元素和inline-block / vertical-align(IE8)

.box-wrap:before {

content: '';

display: inline-block;

height: 100%;

vertical-align: middle;

margin-right: -0.25em; //微调整空格

}

.box {

display: inline-block;

vertical-align: middle;

}

方法二:flex布局(ie8以下不支持)

.box-wrap {

height: 300px;

justify-content:center;

align-items:center;

display:flex;

background-color:#666;

}

方法三:transform(不支持ie8以下)

.box-wrap {

width:100%;

height:300px;

background:rgba(0,0,0,0.7);

position:relative;

}

.box{

position:absolute;

left:50%;

top:50%;

transform:translateX(-50%) translateY(-50%);

-webkit-transform:translateX(-50%) translateY(-50%);

}

方法四:设置:auto(该得方法边缘的非固定宽高,频率50%的父级的宽高。)

.box-wrap {

position: relative;

width:100%;

height:300px;

background-color:#f00;

}

.box-content{

position: absolute;

top:0;

left:0;

bottom:0;

right:0;

width:50%;

height:50%;

margin:auto;

background-color:#ff0;

}
END

←上一篇没有了

下一篇→