I created a side navigation bar and a main content area. I arranged these in a grid layout using display: grid with columns set to 200px. I also wrote a JavaScript script to toggle the class list. When I click the toggle button, the side navigation shrinks, but the main content area maintains the same width. How can I make the main content area fill the full width?
function toggleSidebar() {
const sidebar = document.querySelector('.sidebar');
sidebar.classList.toggle('shrink');
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
height: 100vh;
}
.container {
display: grid;
grid-template-columns: 200px minmax(0,1fr); /* Sidebar takes 200px, main content takes remaining space */
height: 100%;
grid-template-rows: 1fr; /* Only one row for this layout */
}
.sidebar {
background-color: #333;
color: white;
padding: 15px;
overflow: hidden;
transition: width 0.3s ease-in-out; /* Transition effect for shrinking */
}
.sidebar ul {
list-style-type: none;
}
.sidebar ul li {
margin-bottom: 10px;
}
.sidebar ul li a {
color: white;
text-decoration: none;
}
.main-content {
background-color: red;
padding: 20px;
overflow: auto;
}
.sidebar.shrink {
width: 50px; /* Shrinks the sidebar width to 50px */
}
.sidebar.shrink ul {
display: none; /* Hide the links when the sidebar is shrunk */
}
.main-content {
transition: margin-left 0.3s ease-in-out; /* Adjust content area when sidebar shrinks */
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Grid Layout</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button onclick="toggleSidebar()">Toggle Sidebar</button>
<div class="container">
<nav class="sidebar">
<!-- Side Navigation Content -->
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<main class="main-content">
<!-- Main Content Area -->
<h1>Welcome to the main content area</h1>
<p>This area should adjust its size based on the sidebar.</p>
</main>
</div>
</body>
</html>
2
Answers
You need a new
shrink
class to make sure it’s being injected via JavaScript when you close the sidebar.You have to modify the grid container, not the container elements, to show/hide the sidebar.
I leave you an example below: