你需要一个新的
shrink
类,以确保当您关闭侧边栏时,它是通过JavaScript注入的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Sidebar Layout</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button class="toggle-button" onclick="toggleSidebar()">Toggle Sidebar</button>
<div class="container">
<nav class="sidebar">
<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">
<h1>Welcome to the main content area</h1>
<p>This area should adjust its size based on the sidebar state.</p>
</main>
</div>
<script src="script.js"></script>
</body>
</html>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
height: 100vh;
}
.toggle-button {
position: absolute;
top: 10px;
left: 10px;
z-index: 1000;
padding: 10px 20px;
background-color: #333;
color: white;
border: none;
cursor: pointer;
border-radius: 5px;
transition: background-color 0.3s ease-in-out;
}
.toggle-button:hover {
background-color: #555;
}
/* Container Grid Layout */
.container {
display: grid;
grid-template-columns: 200px minmax(0, 1fr); /* Sidebar width and main content fill */
height: 100%;
transition: grid-template-columns 0.3s ease-in-out;
}
/* Sidebar Styling */
.sidebar {
background-color: #333;
color: white;
padding: 15px;
overflow: hidden;
transition: transform 0.3s ease-in-out;
}
.sidebar ul {
list-style-type: none;
}
.sidebar ul li {
margin-bottom: 10px;
}
.sidebar ul li a {
color: white;
text-decoration: none;
}
/* Main Content Styling */
.main-content {
background-color: red;
padding: 20px;
overflow: auto;
}
/* Hidden Sidebar State */
.container.shrink {
grid-template-columns: 0 minmax(0, 1fr); /* Sidebar is hidden, main content takes full width as 0 column is stated here */
}
.sidebar.shrink {
transform: translateX(-200px); /* Completely hide sidebar */
}
function toggleSidebar() {
const container = document.querySelector('.container');
const sidebar = document.querySelector('.sidebar');
// Toggle classes to shrink/hide the sidebar
container.classList.toggle('shrink');
sidebar.classList.toggle('shrink');
}