@(css)[妙瞳]css
咱們常常遇到須要把div中的內容進行水平和垂直居中。因此,這裏介紹一種方法,能夠使div水平居中和垂直居中。html
代碼:app
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>div水平垂直居中</title> <style> *{ margin:0; padding:0; } div.box{ background-color:pink; border:2px solid #000; width:960px; height:500px; margin-left:50px; } </style> </head> <body> <div class="box"> <img src="girl.jpg" alt="美女"> </div> </body> </html>
效果圖:
code
如今先讓圖片在div中水平居中
咱們能夠先給圖片套一層盒子。
代碼:htm
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>div水平垂直居中</title> <style type="text/css"> *{ margin:0; padding:0; } div.container{ background-color:pink; border:2px solid #000; width:500px; height:500px; margin:50px auto; display:table; } div.wrapper{ text-align:center; display:table-cell; vertical-align:middle; } div.wrapper img{ border:1px solid #ddd; } </style> </head> <body> <div class="container"> <div class="wrapper"> <img src="girl.jpg" alt="美女"/> </div> </div> </body> </html>
IE8/Firefox/Chrome/Safari/Opera頁面效果:blog
IE6/IE7頁面效果:圖片
因而可知要作IE6/IE7的兼容:it
代碼:io
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>div水平垂直居中</title> <style type="text/css"> *{ margin:0; padding:0; } div.container{ background-color:pink; border:2px solid #000; width:500px; height:500px; margin:0 auto; display:table; margin-top:20px; } div.wrapper{ text-align:center; display:table-cell; vertical-align:middle; } div.wrapper img{ border:1px solid #ddd; } </style> <!--[if lte IE 7]> <style type="text/css"> div.container{ position:relative; } div.wrapper{ position:absolute; left:50%;top:50%; } div.wrapper img{ position:relative; left:-50%;top:-50%; } </style> <![endif]--> </head> <body> <div class="container"> <div class="wrapper"> <img src="girl.jpg" alt="美女"/> </div> </div> </body> </html>
IE6/IE7效果圖:table
綜上所述,要讓div裏面的內容水平居中,能夠使用text-align:center;
要實現垂直居中,container 的display:table;而wrapper的display:table-cell;同時vertical-align:middle;就能夠實現div裏的圖片水平垂直居中。
假如是多張圖片,要實現居中:
代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>div水平垂直居中</title> <style> *{ margin:0; padding:0; } div.container{ background-color:pink; border:2px solid #000; width:700px; height:500px; margin:0 auto; margin-top:50px; } div.wrapper{ text-align:center; margin-top:28px; } div.wrapper img{ border:1px solid #ddd; width:200px; margin:10px; } </style> </head> <body> <div class="container"> <div class="wrapper"> <img src="girl3.jpg" alt="美女"/> <img src="girl3.jpg" alt="美女"/> <img src="girl3.jpg" alt="美女"/> <img src="girl3.jpg" alt="美女"/> <img src="girl3.jpg" alt="美女"/> <img src="girl3.jpg" alt="美女"/> </div> </div> </body> </html>
IE6/IE7/IE8/Firefox/Chrome/Safari/Opera頁面效果:
div.wrapper中的text-align:center;實現水平居中,margin-top:28px;實現垂直居中。
28px=[500-(200+1+1+10+10)*2]/2,即外層的高度減去裏面的高度,而後除以2,設置margin-top,便可居中。
假若有錯誤或者建議的地方,歡迎指正!-----妙瞳。