Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

วิธีสร้าง Pagination (แบ่งหน้า) ด้วย CSS

สร้าง Pagination Component (แถบเลขหน้า) สำหรับรายการข้อมูลยาว ใช้ลิงก์สำหรับหมายเลขหน้า และสัญลักษณ์ « » สำหรับ Prev/Next

ตัวอย่างโค้ด

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *,*::before,*::after{    box-sizing: border-box; } .pagePagination{    margin: 15px;    display: inline-block;    background-color: rgb(39, 39, 39);    overflow: auto;    height: auto; } .links {    display: inline-block;    text-align: center;    padding: 14px;    color: rgb(178, 137, 253);    text-decoration: none;    font-size: 17px; } .links:hover {    background-color: rgb(100, 100, 100); } .selected{    background-color: rgb(0, 18, 43); } </style> </head> <body> <h1> Page pagination example </h1> <div class="pagePagination"> <a class="links" href="#">«</a> <a class="links selected" href="#">1</a> <a class="links" href="#">2</a> <a class="links" href="#">3</a> <a class="links" href="#">4</a> <a class="links" href="#">5</a> <a class="links" href="#">»</a> </div> <h2>Hover on the above numbers to see effect</h2> </body> </html>

โครงสร้าง

  • Container: .pagePagination พื้นหลังสีเข้ม
  • ลิงก์: « (Prev), 1-5 (Page), » (Next)
  • Active Page: .selected พื้นหลังสีเข้มกว่า
  • Hover: พื้นหลังสีเทา

ขยายเป็น Responsive

@media (max-width: 480px) {
  .links { padding: 10px 12px; font-size: 14px; }
  .pagePagination { margin: 10px; }
}

Accessibility แนะนำ

  • ใช้ <nav aria-label="Pagination">
  • Active page ใส่ aria-current="page"
  • Prev/Next ใส่ aria-label="Previous/Next page"

ผลลัพธ์

แถบสีเข้ม: « 1 2 3 4 5 » หน้าที่ 1 Active สีเข้มกว่า Hover สีเทา