欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

总结CSS3的新特性来总结垂直居中的实现方法分享

程序员文章站 2022-04-08 21:20:00
...
CSS3中的flex布局和before伪元素等特性用来实现垂直居中真的是太方便和优雅了,这里我们就来总结CSS3的新特性来总结垂直居中的实现方法分享:

0.单行内容的居中
只考虑单行是最简单的,无论是否给容器固定高度,只要给容器设置 line-height 和 height,并使两值相等,再加上 over-flow: hidden 就可以了

.middle-demo-1{   
height: 4em;   
line-height: 4em;   
overflow: hidden;   
}

优点:
(1). 同时支持块级和内联极元素
(2). 支持所有浏览器
缺点:
(1). 只能显示一行
(2). IE中不支持<img>等的居中
要注意的是:
(1). 使用相对高度定义你的 height 和 line-height
(2). 不想毁了你的布局的话,overflow: hidden 一定要
为什么?
请比较以下两个例子:

<p style="background: #900; color: #00f; font: bold 12px/24px Helvertica,Arial,sans-serif; height:24px; width:370px;">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
<br/>
<br/>
<p style="background: #090; color: #00f; font: bold 12px/2em Helvertica,Arial,sans-serif; height:2em; width:370px; overflow: hidden;">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>


上一个高度是用的绝对单位px,并且没有隐藏溢出,下一个高度用的单位是相对单位em,并且隐藏了溢出。如果你的浏览器支持放大字体,那么尽情地放大字体,看看会出现什么效果。

1.使用position:absolute(fixed),设置left、top、margin-left、margin-top的属性;

.box{   
    position:absolute;/*或fixed*/
    top:50%;   
    left:50%;   
    margin-top:-100px;   
    margin-left:-200px;   
}

2.利用position:fixed(absolute)属性,margin:auto这个必须不要忘记了;

.box{   
    position: absolute;或fixed
    top:0;   
    rightright:0;   
    bottombottom:0;   
    left:0;   
    margin: auto;   
}

3.利用display:table-cell属性使内容垂直居中;

.box{   

display:table-cell;   

vertical-align:middle;   

text-align:center;   

width:120px;   

height:120px;   

background:purple;   

}


4.使用css3的新属性transform:translate(x,y)属性;

.box{   
    position: absolute;   
    transform: translate(50%,50%);   
    -webkit-transform:translate(50%,50%);   
    -moz-transform:translate(50%,50%);   
    -ms-transform:translate(50%,50%);   
}


5.最高大上的一种,使用:before元素;

.box{   

position:fixed;   

display:block;   

background:rgba(0,0,0,.5);   

}   

.box:before{   

content:'';   

display:inline-block;   

vertical-align:middle;   

height:100%;   

}   

.box.content{   

width:60px;   

height:60px;   

line-height:60px;   

color:red;


6.Flex布局;

.box{   
    display: -webkit-box;   
    display: -webkit-flex;   
    display: -moz-box;   
    display: -moz-flex;   
    display: -ms-flexbox;   
    display: flex;   
    水平居中   
    -webkit-box-align: center;   
    -moz-box-align: center;   
    -ms-flex-pack:center;   
    -webkit-justify-content: center;   
    -moz-justify-content: center;   
    justify-content: center;   
     垂直居中    
    -webkit-box-pack: center;   
    -moz-box-pack: center;   
    -ms-flex-align:center;   
    -webkit-align-items: center;   
    -moz-align-items: center;   
    align-items: center;   
}

以上就是总结CSS3的新特性来总结垂直居中的实现方法分享的详细内容,更多请关注其它相关文章!