了
解
紅
點
最
新
動
態(tài)
和
行
業(yè)
資
訊
如何使用css讓不固定寬高的div水平垂直居中呢?這個問題似乎有很多解決辦法,嘗試了網(wǎng)上的最簡單且兼容低版本瀏覽器的方法,但發(fā)現(xiàn)存在一些小問題,所以寫此文章留存。
1.1、父容器container添加css屬性text-align:center; 子容器center添加css屬性display:inline-block;
1.2、代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>水平居中</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> * { margin: 0; padding: 0; font-size: 12px; color: #FFF; } .container { text-align: center; /*主要代碼*/ width: 800px; height: 200px; margin: 0 auto; background-color: #FF5E53; } .center { display: inline-block; /*主要代碼*/ *display: inline; zoom: 1; /*for ie67*/ padding: 10px; border: 1px solid #FFF; } </style> </head> <body> <div class="container"> <div class="center"> 1、將父級元素設(shè)為text-align: center; 2、自身div設(shè)置為display: inline-block; </div> </div> </body> </html> |
2.1、具體還是看代碼吧!
2.2、代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>水平垂直居中</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> * { margin: 0; padding: 0; font-size: 12px; color: #FFF; } .container { display: table; /*主要代碼*/ *position: relative; /*for ie67*/ background-color: #FF5E53; width: 800px; height: 200px; overflow: hidden; margin: 0 auto; } .content { vertical-align: middle; display: table-cell; text-align: center; /*主要代碼*/ *position: absolute; *top: 50%; *left: 50%; /*for ie67*/ } .center { display: inline-block; /*主要代碼*/ *display: inline; zoom: 1; *position: relative; *top: -50%; *left: -50%; /*for ie67*/ padding: 10px; border: 1px solid #fff; } </style> </head> <body> <div class="container"> <div class="content"> <div class="center"> <img src="http://static.ydcss.com/www/img/logo.png" /><br/> 啦啦啦,啦啦啦,我是賣報的小行家.... </div> </div> </div> </body> </html> |
本文有任何錯誤,或有任何疑問,歡迎留言說明。 宜昌專業(yè)網(wǎng)站設(shè)計制作-我們專注于高端網(wǎng)站建設(shè)-紅點互動