CSS垂直居中

<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 不仅在水平方向上将元素居中,垂直方向上也是如此

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,712评论 1 92
  • 44年前我们就把人类送上月球了,但现在我们仍然无法在CSS中实现垂直居中。 在CSS中对元素进行水平居中是非常简单...
    康斌阅读 16,019评论 9 28
  • 对于最流行的表格布局法和行内块法不去考虑,只考虑用最新的现代CSS去实现 基于绝对定位的解决方案 1.早期解决方法...
    咕咚咚bells阅读 2,206评论 0 0
  • 1.绝对定位居中技术 我们一直用margin:auto实现水平居中,而一直认为margin:auto不能实现垂直居...
    DecadeHeart阅读 5,514评论 0 3
  • 标签:css-常用技巧 table-cell 式将 center 元素的父容器设置为 display:table,...
    练晓习阅读 3,547评论 0 1

友情链接更多精彩内容