2

CSS实现文字垂直居中的7种方法

 1 year ago
source link: https://blog.p2hp.com/archives/8694
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、问题描述: 当高度固定或不固定时,单行或多行文本难以实现垂直居中;

二、解决方法:

1、使用line-height属性,将line-height设置与元素高度等高。

局限性:只适用于单行文本,局限性大。

.box {
    height: 100px;
    line-height: 100px;
    white-space: nowrap;
}

2.padding:设置相等的上下padding值。

局限性:有高度限制时不能垂直居中。

.box{
    padding-top: 30px;
    padding-bottom: 30px;
}

3.绝对定位居中:top:0; bottom:0; left:0; right:0; margin:auto;

元素在过度受限情况下,将margin设置为auto,浏览器会重算margin的值。(过度受限指的是同时设置top/bottom与height或者left/right与width。)

优点:支持响应式,只有这种方法在resize之后仍然垂直居中

缺点:使用绝对定位时元素必须有明确高度,没有显式设置overflow时,内容超过元素高度时会溢出,没有滚动条。IE浏览器不支持

.box{/*display:none;*/
    position:absolute;
    width:200px;
    height:200px;
    top:0;
    bottom:0;
    left:0;
    right:0;
    margin:auto;
    background:#000; 
    resize:both;/*用于设置了所有除overflow为visible的元素*/
    overflow:auto; 
}

4.固定高度定位居中:top: 50%;height: 100px;margin-top: -50px;

优点:代码量少、浏览器兼容性高,支持ie6,ie7
缺点:不支持响应式(不能使用百分比、min/max-width),高度固定。

.parent {
    position: relative;
}

.child {
    position: absolute;
    top: 50%;
    height: 100px;
    margin-top: -50px; /*transform: translateY(-50%);*/
}

5.不固定高度定位居中:top:50%;left:50%;transform:translate(-50%, -50%)

缺点:不支持响应式(不能使用百分比、min/max-width)

.parent {position: relative;}
.child{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%, -50%);
}

6.table-cell方式居中:dispaly:table;display:table-cell;vertical-align:middle;

display:table-cell属性指让标签元素以表格单元格的形式呈现,类似于td标签。

原理:利用表布局特点,vertical-align设置为middle后,单元格中内容中间与所在行中间对齐。

优点:支持任意内容的可变高度、支持响应式布局

缺点: 每一个需要垂直居中的元素都会需要加上额外标签(需要table、table-cell两个额外元素);

IE浏览器不支持

.father{ 
    height:200px; 
    display:table; 
}

.son{
    border:1px solid #000; 
    width:760px;
    vertical-align:middle;
    display:table-cell; /*cell垂直居中,如果外层div不为table则tablecell须有高度*/ 
}

7.弹性盒式布局居中:display: flex;justify-content: center;

优点:真正的垂直居中布局

缺点:ie11才开始支持弹性布局

.box{
    display:-webkit-box;
    display:-moz-box;
    display:-ms-flexbox;
    display: -webkit-flex;
    display:flex; 
    -webkit-align-items:center;
    align-items:center;
    -webkit-justify-content: center;
    justify-content: center;
}

总结

1、只有单行文本时,可以将line-height设置与元素高度等高

2、外层div与内层div高度均固定时,可以使用设置相等的上下padding值;

3、当高度固定时,可以采用固定高度定位居中:top: 50%;height: 100px;margin-top: -50px;此方法对IE浏览器支持较好;

4、当高度不固定时,可以采用弹性盒式布局居中:display: flex;justify-content: center;此方法操作简单,但ie11才开始支持弹性布局;或者采用table-cell方式居中:dispaly:table;display:table-cell;vertical-align:middle;此方法支持任意内容的可变高度,但操作繁琐,并且IE8以上的浏览器才支持;


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK