text-align: center;
/*第一種 行內垂直居中*/ height: 43px; line-height:43px; /*咱們將行距增長到和整個div同樣高 line-height:43px;而後插入文字,就垂直居中了。*/ /*第二種*/ vertical-align:middle; display:table-cell; /*將對象做爲表格單元格顯示 */
margin:0px auto;
/*1,設置position:realitive; 2,設置top:-50%; 3,設置margin-top:....減去此元素的高度的一半+減去此元素的補白+減去此元素的邊框寬度 4,加入此元素有兄弟元素,那+減去兄弟元素的高度 */ position: relative; top: 50%; margin-top: -350px; /*width/2+padding+border +兄弟節點高度200/2px+30px+20px+200*/
<!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> <title></title> <script src="../js/jquery-1.11.1.min.js" type="text/javascript"></script> <style type="text/css"> * { padding: 0px; margin: 0px; } #test1 { margin: 0px auto; padding: 0px; width: 400px; height: 400px; border: 2px solid red; text-align: center; /*會讓此元素的內容和子元素的內容水平居中,注意:此元素和子元素並不水平居中*/ } span { line-height: 200px; /* font-size: 200px;*/ } #test2 { margin: 0px auto; /*會讓此元素水平居中,注意:此元素垂直並不居中*/ position: relative; top: 50%; margin-top: -350px; /*width/2+padding+border 200/2px+30px+20px*/ width: 200px; height: 200px; padding: 30px; border: 20px dotted blue; /* display: table-cell; 此元素內容垂直居中第一種寫法 vertical-align: middle;*/ line-height: 200px; /* 此元素內容垂直居中第二種寫法,和div高度相等設置行高*/ } </style> </head> <body> <div id="test1"> <span>我是test1的span標籤,別弄錯了</span> <div id="test2"> 我是test1的字體內容 </div> </div> </body> </html>