只用 HTML5 與 CSS3,就能做出乾淨俐落的橫向選單列,不必寫一行 JavaScript。這個範例看起來簡單,真正棘手的地方卻都在細節裡:怎麼讓三個項目剛好填滿容器、怎麼讓分隔線看起來精緻、怎麼讓左右兩端跟著外框一起圓角。
三個項目如果單純用 width:33%,總和只有 99%,右側會留下一道縫;若三個都寫 34%,又會溢出換行。實務上的做法是:中間項目佔 33%,最後一個項目佔 34%,把剩下的 1% 補回來。同時用 :first-child 取消第一項的左側圓角與內陰影,用 :last-child 取消最後一項的右側邊框並套用右側圓角。
最後一個項目加上 margin-left:-2px,是為了把 inline-block 元素之間因換行空白產生的縫隙與邊框寬度一起吃掉,讓三欄視覺上完全貼合。這也是為什麼這個選單的 HTML 標籤之間最好不要任意加空白。
box-shadow:1px 0 0 #F1F1F1 inset 的重點在最後的 inset 關鍵字:陰影會畫在元素「內部」而不是外部,於是本該是一條右邊框的線,變成不會撐開寬度的內線,完全不影響 33%/34% 的計算。這比 border-right 更好用的原因是——border 會實際佔用方塊寬度,把百分比配置弄亂。
<!doctype html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>HTML5、CSS3 選單</title>
<style type="text/css">
.jikey_demo { width: 80%; margin: 0 auto; background: #f1f1f1; }
.news_info {
margin-bottom: 5px;
border: 1px solid #bbb;
border-radius: 5px;
box-shadow: 0 1px 0 #f1f1f1;
}
.news_info a {
display: inline-block;
width: 33%;
height: 26px;
font-family: "微軟正黑體", "Segoe UI", sans-serif;
line-height: 26px;
text-align: center;
color: #555;
border-right: 1px solid #ccc;
box-shadow: 1px 0 0 #f1f1f1 inset; /* 內凹分隔線,不佔寬度 */
}
.news_info a:first-child {
width: 33%;
box-shadow: none;
border-radius: 4px 0 0 4px;
}
.news_info a:last-child {
width: 34%; /* 補回 1% */
border-right: none;
margin-left: -2px; /* 抵掉 inline-block 的空白縫隙 */
border-radius: 0 4px 4px 0;
}
.news_info a:hover,
.news_info a.current {
color: #208edd;
background: -webkit-linear-gradient(top, #f9f9f9, #b6b4b4);
background: -moz-linear-gradient(top, #f9f9f9, #b6b4b4);
background: -o-linear-gradient(top, #f9f9f9, #b6b4b4);
background: linear-gradient(to bottom, #f9f9f9, #b6b4b4);
}
</style>
</head>
<body>
<div class="jikey_demo">
<nav class="news_info">
<a class="current" href="/news/">新聞1</a>
<a href="/guide/">新聞2</a>
<a href="/review/">新聞3</a>
</nav>
</div>
</body>
</html>
-webkit-、-moz-、-o- 前綴,標準寫法則是 linear-gradient(to bottom, ...)。現代瀏覽器只需標準寫法即可。transition,滑入時就有淡入效果;若想讓選單在窄螢幕自動堆疊,加上 media query 把 display:inline-block 改為 display:block; width:100% 即可。class="current" 標示;更語義化的做法是加上 aria-current="page",讓螢幕閱讀器也能理解。