CSS实现垂直居中

1.display:table

给父元素加上display:tanle将它的显示方式设置为表格,因此我们可以使用表格的 vertical-align property 属性。

#main{
            display: table;
        }
#cell {
            display: table-cell;
            vertical-align: middle;
        }
<div id="main">
    <div id="cell">
        <div class="content">Content goes here</div>
    </div>
</div>

2.绝对定位

这个方法使用绝对定位的div,把它的top 设置为 50%,top margin 设置为负的 content 高度的一般。这意味着对象必须在 CSS 中指定固定的高度。

#content {
            position: absolute;
            top: 50%;
            height: 240px;
            margin-top: -120px; /* negative half of the height */
        }
<div class="content">Content goes here</div>

3.position

使用一个 position:absolute,有固定宽度和高度的 div。这个 div 被设置为 top:0; bottom:0;。但是因为它有固定高度,其实并不能和上下都间距为 0,因此 margin:auto; 会使它居中。使用 margin:auto;使块级元素垂直居中是很简单的。

#content {
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
            height: 240px;
            width: 70%;
        }
<div class="content">Content goes here</div>

4.line-height

将单行文本置中。只需要简单地把 line-height 设置为那个对象的 height 值就可以使文本居中了。

#content {
    height: 100px;
    line-height: 100px;
}
<div class="content">Content goes here</div>

5.flex

justify-content属性定义了项目在主轴上的对齐方式。

.container {
            display: flex;
            flex-direction: column;
            justify-content: center;
            height: 100px;
        }
<div class="content">Content goes here</div>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,687评论 1 92
  • 收听音频,戳链接,旧号itclan已暂停使用,欢迎关注微信itclanCoder公众号可收听更多音频 前言 关于网...
    itclanCoder阅读 12,533评论 3 30
  • 实现水平居中,比较简单,对于行内元素,设置text-aligin:center;对于块级元素,设置left:0;r...
    晴天小猪L阅读 1,124评论 0 0
  • 外面忽然倾盆大雨,我在王的出租屋内,姜去练车了,王还在午睡。忽然觉得好孤独,忽觉得南京也是异地它乡,换一个居住地就...
    章小阅读 910评论 0 0
  • 慕容煜坤盯着叶知秋看了几眼,说:“这是我们家的事情,和你没有关系!”“慕容大少,你……”叶知秋被这么一冲,有些生气...
    梧桐更兼细雨2016阅读 2,540评论 0 0