Academy / Intermediate Level: HTML and CSS
Intermediate Level Practice: HTML and CSS
Part 2: CSS Grid Practice Exercise
Exercise: Build a CSS Grid Layout
In this exercise, you'll create a responsive grid layout with a header, sidebar, main content, and footer. The sidebar and main content will be displayed in a two-column layout on large screens, but will stack vertically on small screens.
Task:
- Use CSS Grid to create a layout with four areas: header, sidebar, main content, and footer.
- Define the grid layout for larger screens (desktop).
- For smaller screens (mobile), stack all areas vertically.
HTML:
htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Grid Layout</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="grid-container">
<header class="header">Header</header>
<aside class="sidebar">Sidebar</aside>
<main class="main">Main Content</main>
<footer class="footer">Footer</footer>
</div>
</body>
</html>
CSS:
Use CSS Grid to create a responsive layout:
- Define a grid with two columns for larger screens.
- Use a single column layout for smaller screens with the help of media queries.
cssCopy code.grid-container {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-columns: 1fr 3fr;
grid-gap: 10px;
}
.header {
grid-area: header;
}
.sidebar {
grid-area: sidebar;
}
.main {
grid-area: main;
}
.footer {
grid-area: footer;
}
@media (max-width: 600px) {
.grid-container {
grid-template-areas:
"header"
"main"
"sidebar"
"footer";
grid-template-columns: 1fr;
}
}