絕對位置元素的水平垂直置中的方法,定位元素垂直置中

來源:互聯網
上載者:User

絕對位置元素的水平垂直置中的方法,定位元素垂直置中

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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.