1.css實(shí)現(xiàn)居中
缺點(diǎn):需要提前知道元素的寬度和高度。
| <!doctype html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> .box{ width: 600px; height: 400px; position: absolute; left: 50%; top: 50%; border:1px solid #000; background:red; margin-top: -200px; /* 高度的一半 */ margin-left: -300px; /* 寬度的一半 */ } </style></head><body> <div class="box"> </div></body></html> | 
2、css3實(shí)現(xiàn)水平垂直居中
注意:無(wú)論元素的尺寸是多少,都可以居中。不過(guò)IE8以上才兼容這種寫(xiě)法,移動(dòng)端可忽略。
| <!doctype html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> .box{ width: 600px; height: 400px; position: absolute; left: 50%; top: 50%; border:1px solid #000; background:red; transform: translate(-50%, -50%); /* 50%為自身尺寸的一半 */ } </style></head><body> <div class="box"> </div></body></html> | 
3、margin:auto實(shí)現(xiàn)居中
| <!doctype html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> .box{ width: 600px; height: 400px; position: absolute; left: 0; top: 0; right: 0; bottom: 0; border:1px solid #000; background:red; margin: auto; /* 有了這個(gè)就自動(dòng)居中了 */ } </style></head><body> <div class="box"> </div></body></html> | 
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持錯(cuò)新站長(zhǎng)站!
新聞熱點(diǎn)
疑難解答
圖片精選