Creating a fixed sidebar that stays visible while scrolling in CSS involves using the position: fixed
property. Here's a simple example to demonstrate how you can achieve this effect:
html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
margin: 0;
font-family: Arial, sans-serif;
}
/* Container for the entire page content */
.container {
display: flex;
/* Adjust the following values according to your layout */
padding-left: 250px; /* Width of the sidebar */
}
/* Sidebar */
.sidebar {
width: 250px;
height: 100vh;
/* 100% of the viewport height */
position: fixed;
top: 0;
left: 0;
background-color: #111;
padding-top: 20px;
color: #fff;
}
/* Main content */
.main-content {
flex: 1;
padding: 20px;
}
/* Style the content for visibility */
p {
margin-bottom: 15px;
}
</style>
</head>
<body>
<div class="container">
<!-- Sidebar -->
<div class="sidebar">
<h2>Sidebar</h2>
<p>This is a fixed sidebar.</p>
</div>
<!-- Main content -->
<div class="main-content">
<h1>Main Content</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. ...</p>
<!-- Add more content as needed -->
</div>
</div>
</body>
</html>
In this example:
.container
class is a flex container that holds both the sidebar and the main content..sidebar
class has a fixed position (position: fixed;
) with a width of 250px
, and it stays fixed at the top-left corner of the viewport (top: 0; left: 0;
)..main-content
class occupies the remaining space in the container (flex: 1;
), and it adjusts its padding as needed.You can modify the styles according to your specific layout and design requirements.
=== Happy Coding :)