zoukankan      html  css  js  c++  java
  • 绝对定位元素的水平垂直居中的方法

    1.css实现居中

      缺点:需要提前知道元素的宽度和高度。

     1 <!doctype html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>Document</title>
     6     <style>
     7         .box{
     8             width: 600px; 
     9             height: 400px;
    10             position: absolute; 
    11             left: 50%; top: 50%;
    12             border:1px solid #000;
    13             background:red;
    14             margin-top: -200px;    /* 高度的一半 */
    15             margin-left: -300px;    /* 宽度的一半 */
    16         }
    17     </style>
    18 </head>
    19 <body>
    20     
    21     <div class="box">
    22         
    23     </div>
    24 
    25 </body>
    26 </html>

    2、css3实现水平垂直居中

      注意:无论元素的尺寸是多少,都可以居中。不过IE8以上才兼容这种写法,移动端可忽略。

     1 <!doctype html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>Document</title>
     6     <style>
     7         .box{
     8             width: 600px; 
     9             height: 400px;
    10             position: absolute; 
    11             left: 50%;
    12             top: 50%;
    13             border:1px solid #000;
    14             background:red;
    15             transform: translate(-50%, -50%);    /* 50%为自身尺寸的一半 */
    16         }
    17     </style>
    18 </head>
    19 <body>
    20     <div class="box">
    21     </div>
    22 </body>
    23 </html>

    3、margin:auto实现居中

     1 <!doctype html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>Document</title>
     6     <style>
     7         .box{
     8             width: 600px; 
     9             height: 400px;
    10             position: absolute; 
    11             left: 0;
    12             top: 0; 
    13             right: 0; 
    14             bottom: 0;
    15             border:1px solid #000;
    16             background:red;
    17             margin: auto;    /* 有了这个就自动居中了 */
    18         }
    19     </style>
    20 </head>
    21 <body>
    22     <div class="box">
    23     </div>
    24 </body>
    25 </html>

     (转载:http://www.qdfuns.com/notes/21738/93c9220f8fa40767833b80439291b1bd.html)

  • 相关阅读:
    java中分页对象类
    java日期处理类DateUtil
    java日期处理类DateUtil
    Java Socket编程
    MySQL中TIMESTAMPDIFF和TIMESTAMPADD函数的用法
    java中用SAX方式解析xml文件
    First Demo
    软件测试面试/笔试题题库(知识的搬运工,不谢!)
    2017年 6月29 开始博客园之旅--愿自己变得更强大!
    DUIEngine使用Visual Studio 2010编译Debug_Dll版有关Error MSB3073错误解决方案
  • 原文地址:https://www.cnblogs.com/wuxibolgs329/p/6188779.html
Copyright © 2011-2022 走看看