Pelajari cara membuat menu navigasi sidebar yang responsif dengan CSS.
Contoh:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> body { margin: 0; font-family: "Lato", sans-serif; } .sidebar { margin: 0; padding: 0; width: 200px; background-color: #f1f1f1; position: fixed; height: 100%; overflow: auto; } .sidebar a { display: block; color: black; padding: 16px; text-decoration: none; } .sidebar a.active { background-color: #4CAF50; color: white; } .sidebar a:hover:not(.active) { background-color: #555; color: white; } div.content { margin-left: 200px; padding: 1px 16px; height: 1000px; } @media screen and (max-width: 700px) { .sidebar { width: 100%; height: auto; position: relative; } .sidebar a {float: left;} div.content {margin-left: 0;} } @media screen and (max-width: 400px) { .sidebar a { text-align: center; float: none; } } </style> </head> <body> <div class="sidebar"> <a class="active" href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> <a href="#about">About</a> </div> <div class="content"> <h2>Contoh Sidebar Responsif</h2> <p>Contoh ini menggunakan kueri media untuk mengubah sidebar menjadi top navigation bar saat ukuran layar 700px atau kurang.</p> <p>Kami juga telah menambahkan kueri media untuk layar yang berukuran 400px atau kurang, yang akan menumpuk dan memusatkan link navigasi secara vertikal.</p> <h3>Ubah ukuran jendela browser untuk melihat efeknya.</h3> </div> </body> </html>
Membuat Sidebar Responsif
Langkah 1) Tambahkan HTML
Contoh:
<!-- The sidebar --> <div class="sidebar"> <a class="active" href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> <a href="#about">About</a> </div> <!-- Page content --> <div class="content"> .. </div>
Langkah 2) Tambahkan CSS
Contoh:
/* Menu navigasi samping */ .sidebar { margin: 0; padding: 0; width: 200px; background-color: #f1f1f1; position: fixed; height: 100%; overflow: auto; } /* link Sidebar */ .sidebar a { display: block; color: black; padding: 16px; text-decoration: none; } /* link Active/current */ .sidebar a.active { background-color: #4CAF50; color: white; } /* Link pada mouse-over */ .sidebar a:hover:not(.active) { background-color: #555; color: white; } /* Halaman konten. Nilai properti margin-left harus sesuai dengan nilai properti lebar sidebar */ div.content { margin-left: 200px; padding: 1px 16px; height: 1000px; } /* Pada layar yang lebarnya kurang dari 700px, buat sidebar menjadi topbar */ @media screen and (max-width: 700px) { .sidebar { width: 100%; height: auto; position: relative; } .sidebar a {float: left;} div.content {margin-left: 0;} } /* Pada layar yang berukuran kurang dari 400 piksel, tampilkan bar secara vertikal, bukan horizontal */ @media screen and (max-width: 400px) { .sidebar a { text-align: center; float: none; } }