码迷,mamicode.com
首页 > Web开发 > 详细

css实现各种垂直居中的方法

时间:2015-08-11 17:39:08      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

随着接触的项目越来越多,就可以感受到“居中”应用的非常广泛。

水平居中,这里就不多说了,margin:0 auto就可以解决。

最令人烦恼的是垂直居中,这也是本章将重点总结的地方。

下面按类来划分垂直居中的解决方法:

  1.单行文本垂直居中    

代码:

div p{
        line-height: 30px;
        height: 30px;
    }

 

  2.图片居中       

    <div>
        <img src="1.jpg" alt="" />
    </div>
   div{
        width:300px;
        border:1px solid red;
        line-height: 300px;/*重点*/
    }
    
    div img{
        width: 100px;
        height: 100px;
        vertical-align: middle;/*重点*/
    }

 

  3.表格垂直居中       

 

   <div>
        <p>this is content</p>
    </div>
  div{
        display: table;
        border: 1px solid red;
        height: 100px;
        width: 300px;
    }
    div p{
        display: table-cell;
        vertical-align: middle;
    }

  4.块级元素垂直居中       

 

    <div class="blue">
        <div class="red"></div>
    </div>    
  .blue{
        width: 200px;
        height: 200px;
        position: relative;
        background-color: blue;
    }
    .red{
        width: 100px;
        height: 30%;
        position: absolute;
        top: 50%;
        margin-top:-15%; /*margin-top是height的一半*/
        background-color: red;
    }

另一种样式写法

  .blue{
        width: 200px;
        height: 200px;
        position: relative; /*重点*/
        background-color: blue;
    }
    .red{
        width: 100px;
        height: 30%;
        position: absolute;/*重点*/
        top: 0;/*重点*/
        bottom: 0;/*重点*/
        margin:auto;/*重点*/
        background-color: red;
    }

  5.借助空div使容器垂直居中       

 

  <div class="blue">
        <div class="floater"></div>
        <div class="red"></div>
    </div>
  .blue{
        height: 200px;
        width: 200px;
        background-color: blue;
    }
    .red{
        clear: both;
        height: 100px;
        background-color: red;
    }
    .floater{
        float: left;
        height: 50%;
        width: 100%;
        margin-bottom: -50px;/*内容高度的一半*/
    }

  6.利用css3实现垂直居中      

 该中方法IE不兼容

  <div class="blue">
        <div class="red"></div>
    </div>
  .blue{
        width: 300px;
        height: 200px;
        display: -webkit-box; /*重点*/
        -webkit-box-align:center;/*重点*/
        background-color: blue;
    }
    .red{
        width: 100px;
        height: 100px;
        background-color: red;
    }

 

 

 

css实现各种垂直居中的方法

标签:

原文地址:http://www.cnblogs.com/Imever/p/4721116.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!