How to Create a Scrollable Sticky Sidebar
You might have used sites with a sidebar that doesn't move even when you scroll.
Here's a straightforward way to achieve this using just HTML and CSS.
HTML
First, we'll set up a basic HTML structure with a sidebar and a main content area:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sidebar Example</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <div class="sidebar" id="sidebar">Sidebar Content</div> <div class="content">Main Content Goes Here</div> </div> </body> </html>
CSS
Next, add CSS to style the layout and make the sidebar sticky:
/* style.css */ body, html { margin: 0; padding: 0; height: 100%; } .container { display: flex; } .sidebar { position: -webkit-sticky; /* For Safari */ position: sticky; top: 0; height: 100vh; /* Full height of the viewport */ overflow-y: auto; /* Enable scrolling if the sidebar content is tall */ width: 200px; /* Sidebar width */ background-color: #f4f4f4; /* Sidebar background color */ } .content { flex-grow: 1; padding: 20px; height: 200vh; /* Twice the height of the viewport to enable scrolling */ }
This CSS will make the sidebar sticky and scrollable independently of the main content.
The sidebar stays within the viewport when you scroll down the page; if the content inside the sidebar is too long, it will have its scrollbar.
Here's a full example that you can start hacking from:
Happy coding!