css实现div水平垂直居中

作者:Jasmine - 2020年06月17日

水平垂直居中是页面布局中及其常见的样式,有很多种实现方式,下面就介绍常用几种实现方式:

div布局:

<div class="outer">
    <div class="inner"></div>
</div>

初始css:

.outer{
    height:200px;
    width:200px;
    border:1px solid #000;}
.inner{
    height: 100px;
    width:100px;
    border:1px solid #000;}



方法1:采用绝对定位absolute,利用负边距:margin-top,margin-left.

.outer{
    height:200px;
    width:200px;
    border:1px solid #000;
    position:relative;
}
.inner{
    height: 100px;
    width:100px;
    border:1px solid #000;
    position:absolute;
    top:50%;  
    left:50%; 
    margin-left:-50px;
    margin-top:-50px;
}

这种方法,就是要知道div的大小,根据宽高去计算,还是比较常用。


方法2:采用绝对定位,巧妙使用margin:auto

.outer{
    height:200px;
    width:200px;
    border:1px solid #000;
    position:relative;
}
.inner{
    height: 100px;
    width:100px;
    border:1px solid #000;
    position:absolute;
    top:0px;
    bottom: 0px;
    left:0px;
    right:0px;
    margin:auto;
}

这种方法不需要计算top,left的值,比上面那种办法方便许多,用于弹窗的时候定位,或者定位某个元素在父元素上面水平垂直居中。


方法3:采用绝对定位+transform

.outer{
    height:200px;
    width:200px;
    border:1px solid #000;
    position:relative;
}
.inner{
    height: 100px;
    width:100px;
    border:1px solid #000;
    position:absolute;
    top:50%;
    left: 50%;
    transform: translate(-50%,-50%);
}

这种方法主要是用transform的x,y设置为-50%,其实原理跟上面的绝对定位差不多,兼容不大好。


方法4:flex布局

.outer{
    height:200px;
    width:200px;
    border:1px solid #000;
    display: flex;
    justify-content: center;
    align-items: center;
}
.inner{
    height: 100px;
    width:100px;
    border:1px solid #000;
}

这个方法挺好用的,特别是对于手机端布局使用最方便,Flex布局即为弹性布局,只需将父元素设置三个属性即可(display,justify-content,align-items)。


方法5:采用绝对定位,计算定位距离(我平常用比较少的)

.outer{
    height:200px;
    width:200px;
    border:1px solid #000;
    position:relative;
}
.inner{
    height: 100px;
    width:100px;
    border:1px solid #000;
    position:absolute;
    top:50px;   /*(父元素高度-子元素高度)/2*/
    left:50px;  /*(父元素宽度-子元素宽度)/2*/
}

这种方法要根据父子元素的宽高来计算top和left的值,用起来比较麻烦。



本文作者: Jasmine

本文链接: https://www.jianbaizhan.com/article/662

版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!


 请勿发布不友善或者负能量的内容。审查将对发布广告等违规信息进行处罚!