正文 3468字数 260,837阅读

在web页面布局中居中是我们常遇到的情况,而居中分为水平居中与垂直居中

文本的居中
CSS中对文本的居中做的非常友好,我们是需要text-align, line-height 两个属性就可以控制文本的水平以及垂直居中
<head> <style type="text/css"> .text { width: 200px; height: 200px; border: 1px solid green; text-align: center; line-height: 200px; } </style> </head> <body> <div class="text">文本的水平垂直居中</div> </body> </html>
Run code
Cut to clipboard

    注意:line-height属性控制文本的垂直方向居中时 只使用单行文本的情况,多行文本时不能采用次方法

    元素的居中
    在CSS 中对于元素的居中,相信写过CSS的同学对于其中的垂直居中都觉得非常苦恼,下面我们来看下实现居中的几种方法

    方法一:
    使用display:table-cell 来居中,通过display:table-cell 来把他模拟成一个表格的单元格,利用表格的居中特性
    <head> <style type="text/css"> .parent { display: table-cell; width: 200px; height: 200px; vertical-align: middle; text-align: center; border: 1px solid red; } .child { display: inline-block; background-color: #33F; } </style> </head> <body> <div class="parent"> <div class="child">元素的水平居中</div> </div> </body> </html>
    Run code
    Cut to clipboard

      注意:当前方法兼用 IE8+ 谷歌,火狐等

      方法二:
      使用绝对定位来居中,原理为设置定位元素的left与top为50%,但是这时候元素还不是居中的,因为坐标计算是根据元素的左上角的顶点计算的

      所以相对中间的位置偏移了元素宽度/高度一半的距离,不过我们只需要设置元素的margin-top,margin-left 为负值就行了,值为元素宽/高的一半
      <head> <style type="text/css"> .parent { position: relative; width: 200px; height: 200px; border: 1px solid green; } .child { margin-left: -50px; margin-top: -50px; position: absolute; top: 50%; left: 50%; width: 100px; height: 100px; background-color: #33F; } </style> </head> <body> <div class="parent"> <div class="child"></div> </div> </body> </html>
      Run code
      Cut to clipboard

        注意: 此方法只能使用宽度高度已知的元素

        方法三:
        另一种绝对定位的方法
        <head> <style type="text/css"> .parent { position: relative; width: 200px; height: 200px; border: 1px solid green; } .child { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; width: 50px; height: 50px; background-color: #33F; } </style> </head> <body> <div class="parent"> <div class="child"></div> </div> </body> </html>
        Run code
        Cut to clipboard

          注意:此方法也是只适用于有元素有固定宽高的情况,而且只支持IE9+ 谷歌,火狐等符合w3c标准的“现代浏览器”

          <!--盒子自动居中 类 middlesjs 加最后--> <style> .middlesjs{width:auto;display: inline-block;}</style> <script> //自动居中 $(document).ready(function(){ $(".middlesjs").each(function(){ var nw=$(this).width(); $(this).css({'left':'50%','margin-left':'-'+(nw/2)+'px','position':'relative'}); }); }); </script> <!--end--> <div class="bt1 middlesjs">
          Run code
          Cut to clipboard