這個範例示範如何做出入口網站常見的「分頁式資訊區」:幾個標籤橫排,點哪一個就顯示對應的內容區塊,其餘隱藏。原始碼中 JavaScript 的部分未完整收錄,以下聚焦在真正有價值、也最容易學錯的 CSS 版面部分。
BODY {
MARGIN: 6px 0px;
FONT: 12px 新細明體;
TEXT-ALIGN: center;
}
.divArea3 { WIDTH: 750px }
.divArea3 .divAreaCol1 { FLOAT: left; WIDTH: 371px }
.divArea3 .divAreaCol2 { FLOAT: right; WIDTH: 280px }
.divArea3Box {
border: 1px solid #cccccc;
padding: 2px;
margin: 2px 0;
width: 100%;
line-height: 120px;
height: 120px;
text-align: center;
}
A { color: #999999; text-decoration: none }
.tabWin {
width: 371px;
height: 230px;
border: 1px solid #cccccc;
display: inline;
float: left;
margin: 0 3px;
overflow: hidden; /* 內容超出就裁掉,維持固定高度 */
}
.tabWinInnerBox {
margin: 5px;
overflow: hidden;
width: 361px;
height: 220px;
}
/* 標籤列與分隔線 */
.tabWinLine1 { width: 360px; height: 29px }
.tabWinLine2 { display: block; width: 360px; height: 1px }
.tabWinLine4 { display: none; width: 360px; height: 1px }
.tabWinLine2 DIV,
tabWinLine4 DIV {
float: left;
width: 118px;
height: 1px;
background-color: #cccccc;
}
/* 標籤按鈕 */
.tabWinLine1 DIV {
font-weight: bold;
float: left;
background-image: url(images/c21_1.gif);
width: 118px;
cursor: pointer;
color: #1f3a87;
line-height: 26px;
height: 26px;
}
/* 選中的那一頁 */
.tabWinLine1 .tabWinTitle {
border: 1px solid #cccccc;
background-image: url(images/0.gif);
width: 116px;
color: #b10000;
height: 28px;
background-color: white;
}
/* 內容塊 */
.tabWinInnerBox .showblock {
border: 1px solid #cccccc;
padding: 3px 7px 8px;
margin: 0 0 3px;
overflow: hidden;
width: 348px;
}
用 1px 的負壓讓標籤與內容框接合。選中的標籤寬 116px、高 28px,比未選中的 118×26 少 2px,再靠 1px 邊框補回來,視覺上就與下方內容框連成一體——這是分頁元件最經典的錯位手法。
用 display 在兩條分隔線之間切換。.tabWinLine2 顯示、.tabWinLine4 隱藏,切換標籤時一起對調,就能做出「選中頁的下方沒有分隔線」的效果。
用 overflow:hidden 鎖住高度。固定 230px 的高度搭配隱藏溢出,能讓不同長度的內容區塊維持一致的版面,不會因為切頁而整頁跳動。
用 cursor:pointer 明示可互動。這裡標籤是用 <div> 加 onclick 做的,所以必須手動加上手型游標,否則使用者不會知道它能點。
用 <div> 加 cursor:pointer 做標籤,有幾個實際問題:鍵盤無法聚焦、螢幕閱讀器讀不出「這是分頁」、也無法用左右鍵在標籤間移動。正確做法是用 ARIA 的 tablist 模式:
<div class="tabs" role="tablist" aria-label="資訊分類">
<button role="tab" id="tab-1" aria-controls="panel-1" aria-selected="true">最新消息</button>
<button role="tab" id="tab-2" aria-controls="panel-2" aria-selected="false" tabindex="-1">熱門文章</button>
</div>
<section role="tabpanel" id="panel-1" aria-labelledby="tab-1">內容一</section>
<section role="tabpanel" id="panel-2" aria-labelledby="tab-2" hidden>內容二</section>
.tabs { display: flex; border-bottom: 1px solid #ccc; }
.tabs [role="tab"] {
padding: 6px 14px;
border: 1px solid #ccc;
border-bottom: none;
background: #f2f2f2;
cursor: pointer;
}
.tabs [aria-selected="true"] {
background: #fff;
color: #b10000;
font-weight: bold;
margin-bottom: -1px; /* 壓住外框線,就是原版的負壓技巧 */
}
[role="tabpanel"]:focus { outline: none; }
用 display:flex 取代了整組 float 加 display:inline 的 hack,寬度不必再寫死;margin-bottom:-1px 則完整保留了原版那個「選中標籤與內容框接合」的視覺。再加上 aria-selected 與 hidden 屬性,輔助技術就能正確理解哪個面板正在顯示。
最後記得補上鍵盤操作:左右方向鍵切換標籤、Home 與 End 跳到首尾,並在切換時同步更新 aria-selected 與 tabindex。這些都是分頁元件該有的基本行為,原版的 <div> 寫法完全做不到。