萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

XHTML 三欄式版面實戰:語意化結構與 CSS Float 佈局

語意化 HTML 結構

<!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" lang="zh-TW" xml:lang="zh-TW">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>三欄式版面</title>
  <link rel="stylesheet" type="text/css" href="style.css" media="screen,projection" />
</head>
<body>
  <div id="header"><h1>頁首</h1></div>
  <div id="container">
    <div id="sidebar-left"><h2>左側欄</h2></div>
    <div id="main-content"><h2>主內容</h2></div>
    <div id="sidebar-right"><h2>右側欄</h2></div>
  </div>
  <div id="footer"><p>頁尾</p></div>
</body>
</html>

CSS 佈局 (Float 方案)

* { box-sizing: border-box; margin: 0; padding: 0; }
#header { width: 100%; height: 120px; background: #0074c8; text-align: center; padding-top: 20px; }
#container { width: 100%; overflow: hidden; /* 清除浮動 */ }
#sidebar-left  { width: 33.3%; height: 500px; float: left; background: #ffff99; }
#main-content  { width: 33.4%; height: 500px; float: left; background: #ffffcc; border-left: 1px solid #ccc; border-right: 1px solid #ccc; }
#sidebar-right { width: 33.3%; height: 500px; float: left; background: #ffff99; }
#footer { width: 100%; height: 70px; background: #0074c8; text-align: center; padding-top: 20px; clear: both; }
h1,h2,p { color: #333; }

關鍵技巧與跨瀏覽器坑

  • 寬度加總 ≤ 100%:邊框、內距會增加實際寬度,`box-sizing:border-box` 讓 width 包含 padding/border。
  • IE6 雙邊距 Bug:浮動元素同方向 margin 會加倍,修正 `display: inline;`。
  • 清除浮動:父容器 `overflow:hidden` 或 `:after { content:""; display:block; clear:both; }`。
  • 等高欄:偽欄背景圖、負 margin + padding 大法、或改用 Flexbox/Grid(現代專案首選)。

現代寫法:Flexbox / Grid 一行搞定

/* Flexbox */
#container { display: flex; }
#sidebar-left { flex: 0 0 33.33%; }
#main-content { flex: 0 0 33.34%; }
#sidebar-right { flex: 0 0 33.33%; }

/* Grid */
#container { display: grid; grid-template-columns: 1fr 1fr 1fr; }

無需浮動、自動等高、響應式輕鬆切換欄數。

copyright © 萬盛學電腦網 all rights reserved