margin:0px auto;適用於指定了固定寬度的div與其它元素,好比p,img等,使用 margin:0px auto,居中是你們在作css div定位時的最經常使用方法,可是據我本身的使用過程來看,常有居中不了的狀況。css
這種狀況下,由於前面設了margin:0px auto; 可是後面又設了margin:100px,這明顯是相矛盾的,不只如此,若是同時使用了margin:0px auto ; 和 float:left ,也同樣都不生效。html
DOCTYPE是指定瀏覽器以哪種標準解析html代碼,若是不指定,極有可能會不生效。瀏覽器
咱們常見有人寫html,是直接以<html>開頭的,這種狀況,咱們只要再加上DOCTYPE頭便可以,最好是直接從dw中新建一個html頭,而後從中再作修改。完整的html頭以下:ui
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>無標題文檔</title> </head> <body> 主題內容 </body> </html>
我試了一下,只要在<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">這一句前加了一個<!-- 說明文字 -->這樣的註釋,也一樣出現了margin:0px auto;沒法居中的狀況。spa
這是下下之策,若是上面margin:0px auto;用了怎麼都不行,那到body中加上text-align:center;吧,如此一下不只是div,文字也會居中顯示。
而後能夠再到細化的css中,把相應容器再設成text-align:left再達到文字靠左的效果。code使用 text-align:center; 居中時不能添加 doctype 聲明,不然將不生效 xml
還有就是 margin:0 auto; 和 margin-left:auto; margin-right:auto;的現實效果有時還不同,其原意可能在於設置了margin-top的高度不爲0時,會出現意想不到的效果。htm