一直遇到各种垂直居中的问题,今天就一起来整理一下各种垂直居中的处理方法。

对于行内元素

一般而言行内元素比较简单,一般采用以下思路对父元素写CSS即可

1         #wrap{
2             text-align: center;
3             line-height: 100px;
4             height: 100px;
5         }

 

对于块级元素

块级元素实现垂直居中的方法多种多样,视具体情况而选择

 

本次讨论的HTML代码如下

1     <div id="wrap">
2         <div id="inside">
3         </div>
4     </div>

 

div定宽高情况可直接用absolute定位解决

 1         #wrap{
 2             position: relative;
 3             width: 400px;
 4             height: 400px;
 5             background-color: cadetblue;
 6         }
 7 
 8         #inside{
 9             position: absolute;
10             width: 100px;
11             height: 100px;
12             margin-left: 150px;
13             margin-top:  150px;
14             background-color: green;
15         }

 

margin:auto的应用解决垂直居中

 1         #wrap{
 2             position: relative;
 3             background-color: cadetblue;
 4         }
 5 
 6         #inside{
 7             position: absolute;
 8             margin: auto;
 9             top: 0;
10             bottom :0;
11             left: 0;
12             right: 0;
13             background-color: green;
14         }

 

CSS3 transfrom实现垂直居中

 1         #wrap{
 2             position: relative;
 3             background-color: cadetblue;
 4         }
 5 
 6         #inside{
 7             position: absolute;
 8             top:50%;
 9             left: 50%;
10             transform: translate(-50%,-50%);
11             background-color: green;
12         }

 

flexbox实现垂直居中

1         #wrap{
2             display: flex;
3             justify-content: center;
4             align-items: center;
5             background-color: cadetblue;
6         }

 

flexbox的概念随着浏览器的更新以及移动端浏览器对于其良好的兼容性而变得越来越火,而伴随着一系列老版本IE的离开相信未来flexbox会大放异彩。

 

最后放上所有垂直居中的成果。

 

 posted on 2017-01-13 17:39  葱头儿  阅读(122)  评论(0)    收藏  举报