規劃好頁面布局後,接下來就是把整體的層結構與 CSS 寫出來。本文示範如何從零建立一個 DIV+CSS 頁面骨架。
先在桌面新建一個文件夾,命名為「DIV+CSS布局練習」,在其中新建兩個空文件。第一個寫入 XHTML 基本結構:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="https://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html;charset=gb2312"/>
- <title>無標題文檔</title>
- <link href="css.css" rel="stylesheet" type="text/css"/>
- </head>
- <body></body>
- </html>
將其命名為 index.htm,另一個文件命名為 css.css。
在 body 標籤對中寫入 DIV 骨架:
- <div id="container"><!--頁面層容器-->
- <div id="Header"><!--頁面頭部--></div>
- <div id="PageBody"><!--頁面主體-->
- <div id="Sidebar"><!--側邊欄--></div>
- <div id="MainBody"><!--主體內容--></div>
- </div>
- <div id="Footer"><!--頁面底部--></div>
- </div>
養成寫註釋的習慣,能讓日後閱讀代碼更輕鬆。接著打開 css.css 寫入樣式:
- /*基本信息*/
- body{font:12px Tahoma;margin:0px;text-align:center;background:#FFF;}
- /*頁面層容器*/
- #container{width:100%}
- /*頁面頭部*/
- #Header{width:800px;margin:0 auto;height:100px;background:#FFCC99}
- /*頁面主體*/
- #PageBody{width:800px;margin:0 auto;height:400px;background:#CCFF00}
- /*頁面底部*/
- #Footer{width:800px;margin:0 auto;height:50px;background:#00FFFF}
保存後用瀏覽器打開,就能看到基礎框架了。
font:12px Tahoma;是縮寫,完整寫法為 font-size:12px; font-family:Tahoma;。
margin:0px;是四個方向外边距的縮寫,順序為上/右/下/左,也可寫成 margin:0。margin:0px auto 則表示上下為 0、左右自動,從而使層居中。
text-align:center;文字居中對齊。
background:#FFF;設置背景色為白色,完整寫法為 #FFFFFF。background 還可搭配 url、定位與 repeat 等參數控制背景圖片。
至於頁面為何居中?關鍵在 #container 中的 margin:0 auto;,左右自動調整即讓層居中;若要居左,去掉 auto 即可,因為默認就是居左。