DIV CSS垂直居中显示技巧

手册/FAQ (431) 2015-10-22 13:42:04

       在我们做网页时,有时需要DIV垂直居中显示,DIV垂直居中显示不会像DIV水平居中显示那样,单单可以通过margin就能设置。下面教大家DIV水平居中显示是怎么做出来的。


<html>

      <head>

            <title>CSS DIV垂直居中显示技巧</title>

            <style>

               .div{

                     position:absolute;

                     width:500px;

                     height:300px;

                     left:50%;

                     top:50%;

                     margin-left:-250px;

                     margin-top:-150px;

                     border:1px solid #f00;

               }

            </style>

      </head>

      <body>

         <div class="div">DIV水平居中和上下垂直居中显示</div>

      </body>

</html>


DIV垂直居中显示解说:
方法中使用了position:absolute绝对定位,页面左边left和上边top设为50%,如果直接设为50%是实现不了垂直居中显示的,还要设置DIV左边距和上边距为DIV宽度和高度的负一半。比如width:500px、height:300px,要设margin-left:-250px、height:-150px,就可以实现DIV水平和垂直居中显示效果。

 

THE END