1.css實現(xià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實現(xiàn)水平垂直居中
注意:無論元素的尺寸是多少,都可以居中。不過IE8以上才兼容這種寫法,移動端可忽略。
<!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實現(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; /* 有了這個就自動居中了 */ } </style></head><body> <div class="box"> </div></body></html>
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持VeVb武林網(wǎng)!
新聞熱點
疑難解答