Blog Details
Md. Asadur Rahman
17 Oct 2024
1 min read
CSS Grid is a two-dimensional layout system that allows you to control both rows and columns in a grid container. You can create responsive layouts with flexible grid items that adjust according to screen size.
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: auto;
gap: 20px;
}
.grid-item {
background-color: #f0f0f0;
padding: 20px;
text-align: center;
}
Flexbox is a one-dimensional layout system that helps control the alignment, distribution, and spacing of items inside a container. It's perfect for handling rows or columns individually.
.flex-container {
display: flex;
justify-content: space-between;
align-items: center;
}
.flex-item {
background-color: #ccc;
padding: 10px;
}
Let’s start by setting up a simple layout that uses both Grid and Flexbox for a responsive page structure.
grid-template-areas
define different regions of the layout.grid-template-columns: 1fr 3fr 1fr
sets up the layout with a flexible sidebar, main content, and navigation.header
, footer
, nav
, and sidebar
to align and space out the content properly.HTML Structure:
<div class="grid-container">
<header class="grid-item header">Header</header>
<nav class="grid-item nav">Navigation</nav>
<main class="grid-item main">Main Content</main>
<aside class="grid-item sidebar">Sidebar</aside>
<footer class="grid-item footer">Footer</footer>
</div>
CSS (Grid for Layout, Flexbox for Content Alignment):
/* Grid Layout */
.grid-container {
display: grid;
grid-template-areas:
"header header header"
"nav main sidebar"
"footer footer footer";
grid-template-columns: 1fr 3fr 1fr;
grid-template-rows: auto 1fr auto;
gap: 20px;
height: 100vh;
}
.header { grid-area: header; }
.nav { grid-area: nav; }
.main { grid-area: main; }
.sidebar { grid-area: sidebar; }
.footer { grid-area: footer; }
/* Flexbox for Alignment Inside Grid Items */
.header, .footer {
display: flex;
justify-content: center;
align-items: center;
}
.nav, .sidebar {
display: flex;
flex-direction: column;
justify-content: space-around;
}
Don’t worry, we don’t spam!