數字分頁是列表頁的標準配備。以下示範如何只用 CSS 完成,包含滑鼠移入時放大並浮於上層的效果。
<!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">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>CSS 數字分頁</title>
<style type="text/css">
ul { list-style: none; }
ul li {
float: left;
width: 22px;
height: 22px;
margin-left: 5px;
}
a {
width: 20px;
height: 20px;
display: block;
text-align: center;
text-decoration: none;
background-color: white;
border: 1px solid #666;
}
a:hover {
width: 40px;
height: 30px;
border: 1px solid #666;
position: absolute;
line-height: 30px;
margin: -5px 0 0 -10px;
}
</style>
</head>
<body>
<ul>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li><a href="#">6</a></li>
<li><a href="#">7</a></li>
</ul>
</body>
</html>
第一步:讓 li 浮動,使數字水平排列。
第二步:把 a 設為 display: block 並給定寬高,這樣整塊區域都可點擊,而不只是文字本身。
第三步:用 :hover 放大 a,並以 position: absolute 脫離文檔流,讓放大的方塊能覆蓋在相鄰元素之上。負的 margin 用來抵消失大後產生的位移,使中心點維持原位。
關鍵細節:a 的背景色必須設為不透明(這裡是白色)。因為 a 預設背景透明,放大後會透出下方被遮住的相鄰邊框,看起來像破了一個洞。
用 flexbox 可以省掉浮動與清除,也不需要為每個項目設定固定寬度:
ul {
display: flex;
gap: 5px;
list-style: none;
padding: 0;
}
a {
display: block;
min-width: 22px;
padding: 0 6px;
text-align: center;
text-decoration: none;
border: 1px solid #666;
transition: transform .15s;
}
a:hover { transform: scale(1.4); }
transform: scale() 不會影響排版,因此不必再手動算 margin 偏移,也不必設 position: absolute。
別忘了標示目前頁與導航語意:
<nav aria-label="分頁導航">
<a href="?page=1" aria-current="page">1</a>
<a href="?page=2">2</a>
</nav>