技术分享CSS

使用display:table-cell实现垂直居中

2017-05-27  本文已影响140人  逗比二二二

常用的垂直居中办法

这里就随便列几个自己常用的,其实方法有很多,这里不谈flex

1. 子元素高度固定
html:

<div class="parent">
    <div class="child">balabala</div>    
</div>

css:

.parent {
     position: relative;
}
.child {
    position: absolute;
    height: 50px;
    top: 0;
    bottom: 0;
    margin: auto 0;
}

当然这只是一种方法,还可以使用负margin等。

2. 单行文本在父元素中垂直居中,父元素高度固定
html:

<div class="parent">
    <p class="child">不超过一行的文本</p>
</div>

css:

.parent {
    width: 500px;
    height: 100px;
}
.child {
    line-height: 100px;
}

3. 子元素高度不固定,父元素高度固定
html:

<div class="parent">
    <div class="child">不知道有多高</div>
</div>

css:

.parent {
    height: 500px;
    position: relative;
}
.child {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

讲重点

先丢个张鑫旭大佬的链接,里面讲了很多display:table-cell相关的

假如我现在有一个div,高度固定,里面有一段文本,差不多跟上面的第二个差不多,但是不知道到底有多少行。如果用第二种方法,并且文本超过了一行,那肯定超出父元素了,如图

文本两行,父元素高300px,line-height:300px

我们不可能用这么大的line-height去显示文本,对吧,那我现在lihe-height设成2,嗨呀,不垂直居中了,好气(当然这种情况用transform的方法也能解决)

line-height为2
不废话,拿起display:table就开始干
.parent {
    display: table;
    height: 300px;
    width: 100%;
}
.child {
    line-height: 2;
    display: table-cell;  /* 类似于表格中的单元格 */
    vertical-align: middle;
}
垂直居中,完美

注意,此时的child已经变味跟单元格类似,所以margin什么的已经没用啦

margin无效

这可能是最简单的场景了,稍微复杂一点,比如下面这种会经常遇到


文章列表,图片与右侧文字对齐

转载请注明:http://www.jianshu.com/p/a7ee7dd60166

上一篇下一篇

猜你喜欢

热点阅读