CSS
Responsive Two-Column Layout with Flexible Sidebar using CSS Grid
Build a flexible two-column web layout using CSS Grid, allowing a sidebar to adapt its width and position dynamically on different screen sizes with media queries.
.grid-container {
display: grid;
grid-template-columns: 1fr 300px; /* Main content takes available space, sidebar is 300px */
gap: 20px;
height: 100vh;
padding: 20px;
background-color: #f4f4f4;
box-sizing: border-box;
}
.main-content {
background-color: #ffffff;
padding: 25px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.sidebar {
background-color: #34495e;
color: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
/* Responsive adjustments for smaller screens */
@media (max-width: 768px) {
.grid-container {
grid-template-columns: 1fr; /* Stack columns vertically on small screens */
grid-template-rows: auto auto; /* Content then sidebar */
}
.main-content {
order: 2; /* Put main content after sidebar on small screens */
}
.sidebar {
order: 1; /* Put sidebar first on small screens */
}
}
/* Example usage in HTML:
<div class="grid-container">
<div class="main-content">
<h1>Main Content Area</h1>
<p>This area takes up the flexible space.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
<div class="sidebar">
<h2>Sidebar</h2>
<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
</ul>
</div>
</div>
*/
How it works: This snippet creates a responsive two-column layout using CSS Grid. On larger screens, `grid-template-columns: 1fr 300px` sets the main content to take the remaining space (`1fr`) and the sidebar to have a fixed width of 300px. A media query is used to transform the layout on screens smaller than 768px. It changes `grid-template-columns` to `1fr` to stack the columns vertically, and `order` properties are used on `.main-content` and `.sidebar` to visually reorder them, placing the sidebar above the main content on small screens for better mobile user experience.