美文网首页
CSS垂直居中

CSS垂直居中

作者: cfighter | 来源:发表于2017-02-23 09:53 被阅读0次
<div class="container">
    <div class="content"></div>
</div>

固定高度

1、绝度定位:left/top:50% margin-top\left为元素高宽的一半的负值

.container{
    position:relative;
    width:200px;
    height:200px;
}
.content{
    position:absolute;
    width:50px;
    height:50px;
    left:50%;
    top:50%;
    margin-left:-25px;
    margin-top:-25px;
}

2、借助calc()等价于第1种方法

.container{
    position:relative;
    width:200px;
    height:200px;
}
.content {
    position: absolute;
    top: calc(50% - 3em);
    left: calc(50% - 9em);
    width: 18em;
    height: 6em;
}

3、margin:auto;left/right/top/bottom为0

.container{
    position: relative;
    height: 200px;
    width: 200px;
}
.content{
    position: absolute;
    left:0;
    right:0;
    top:0;
    bottom:0;
    margin: auto;
    width: 100px;
    height:100px;
}

4、单行居中 height= line-height

.content{
    height:40px;
    line-height:40px;
    text-align:center;
}

不固定高度

1、translate

.container{
    position:relative;
    width:200px;
    height:200px;
}
.content{
    position:absolute;
    width:50px;
    height:50px;
    left:50%;
    right:50%;
    transform:translate(-50%,-50%);
}

2、table-cell

.container{
    display:table;
    width:200px;
    height:200px;
    text-align:center;
}
.content{
   display:table-cell;
   vertical-align:middle;
}

3、上下padding相等

.content{
    padding-top:50px;
    padding-bottom;50px;
    text-align:center;
}

4、先给这个待居中元素的父元素设置display:flex,再给这个元素自身设置margin: auto

.container {
    display:flex;
}
.content {
    margin: auto;
}

请注意,当我们使用Flexbox 时,margin: auto 不仅在水平方向上将元素居中,垂直方向上也是如此

相关文章

网友评论

      本文标题:CSS垂直居中

      本文链接:https://www.haomeiwen.com/subject/vovvwttx.html