HTML & CSSMedium
What is CSS Grid?
CSS Grid is a two-dimensional layout system: a grid container (display: grid) defines rows and columns, and children are placed into the resulting cells, automatically or explicitly by line numbers or named areas. It is ideal for page layouts, dashboards, galleries and any design where rows and columns must line up.
Defining the grid
grid-template-columns: 200px 1fr 1fr;: tracks can usepx,%,fr(a fraction of free space),auto,min-content,max-content.repeat(3, 1fr)andminmax(200px, 1fr)for flexible tracks.gap: 16pxfor gutters.grid-template-areasgives a readable ASCII-art layout.
Placing items
- Automatic placement fills cells in order (
grid-auto-flow: densebackfills gaps). grid-column: 1 / -1spans all columns;grid-column: span 2spans two.grid-area: sidebarplaces an item into a named area.
The famous responsive one-liner
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
It creates as many columns as fit, with no media queries. auto-fit collapses empty tracks so items stretch.
Modern features
- Subgrid (
grid-template-columns: subgrid) lets nested elements align to the parent grid, e.g. card titles and footers lining up across cards. - Alignment:
place-items: center,justify-items,align-self. - Masonry layout is being standardized.
Accessibility
Visual placement does not change DOM order; keep source order logical for keyboard and screen reader users.
Code example
html
1<style>2 body { font-family: system-ui; margin: 0; }3 .page {4 display: grid; gap: 8px; min-height: 260px; padding: 8px;5 grid-template-columns: 160px 1fr;6 grid-template-rows: auto 1fr auto;7 grid-template-areas:8 "header header"9 "sidebar main"10 "footer footer";11 }12 .page > * { border: 2px solid #0b1020; padding: 8px; border-radius: 6px; }13 header { grid-area: header; background: #0b1020; color: white; }14 aside { grid-area: sidebar; background: #fef9c3; }15 main { grid-area: main; }16 footer { grid-area: footer; background: #e5e7eb; }17 .gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(90px, 1fr)); gap: 6px; }18 .gallery div { aspect-ratio: 1; background: #2b4bff; border-radius: 6px; }19 .gallery .wide { grid-column: span 2; background: #e11d48; aspect-ratio: auto; }20 @media (max-width: 500px) {21 .page { grid-template-columns: 1fr; grid-template-areas: "header" "main" "sidebar" "footer"; }22 }23</style>24<div class="page">25 <header>Header</header>26 <aside>Sidebar</aside>27 <main>28 <p>Responsive gallery, no media query:</p>29 <div class="gallery"><div></div><div class="wide"></div><div></div><div></div><div></div><div></div></div>30 </main>31 <footer>Footer</footer>32</div>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.