Hey there! If you've ever felt like CSS Grid is a bit like trying to solve a Rubik's Cube blindfolded, you're not alone. I'm Eleftheria, and today, I'm here to help you navigate CSS grid with ease. Let's dive in. ?
Introduction to CSS Grid
CSS Grid is made to allow you to create complex, two-dimensional layouts that were previously quite a headache to achieve. Before Grid, we were juggling with floats, tables, or flexbox for layouts. Grid came along and said, "Hold my beer," offering a more intuitive and powerful way to structure web pages.
Why Learn CSS Grid?
-
Efficiency
: Grid simplifies the way you design layouts, reducing the need for nested elements just for layout purposes. -
Flexibility
: It's fantastic for responsive design, adapting beautifully to different screen sizes. -
Power
: With Grid, you can align elements both vertically and horizontally with ease, which was a nightmare with older methods.
The Basics of CSS Grid
Let's start at the very beginning. To use CSS Grid, you need to define a container as a grid. For example:
.container { display: grid;}
This simple line turns the .container into a grid container, which means its direct children will become grid items.
Creating Grid Columns and Rows
You define grid structure by specifying columns and rows:
.grid-container { display: grid; grid-template-columns: 1fr 1fr 1fr; /* Three columns with equal width */ grid-template-rows: auto auto auto; /* Three rows with automatic height */ }
Here, 1fr means one fraction of the available space, making columns equal in width.
Placing Items in the Grid
You can place items in specific areas using grid-column and grid-row properties:
.item-a { grid-column: 1 / 3; /* Start at line 1, end at line 3 */ grid-row: 1 / 2; /* Span from line 1 to line 2 */ }
This places .item-a starting from the first column line to the third, and through the first row.
Grid Lines and Areas
You can name lines for easier reference:
.grid-container { grid-template-columns: [start] 1fr [line2] 1fr [end]; grid-template-rows: [row1-start] auto [row2-start] auto [row3-end]; }
Then use these names:
.item-b { grid-column: start / line2; grid-row: row1-start / row2-start; }
Grid Areas
For a more visual approach, you can name areas:
.grid-container { display: grid; grid-template-areas: "header header header" "sidebar main main" "footer footer footer"; }
Then assign elements to these areas:
<div class="grid-container"> <div class="header">Header</div> <div class="sidebar">Sidebar</div> <div class="main">Main</div> <div class="footer">Footer</div> </div>
.header { grid-area: header; } .sidebar { grid-area: sidebar; } .main { grid-area: main; } .footer { grid-area: footer; }
More Examples of CSS Grid in Action
1. Responsive Layout with Media Queries
One of the strengths of CSS Grid is its ease in handling responsive designs. Here's an example that shows how to adjust grid layouts for different screen sizes
:.grid-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; } @media (max-width: 768px) { .grid-container { grid-template-columns: 1fr; } }
This setup creates a grid where each item is at least 300px wide but grows to take up available space. On screens smaller than 768px, it shifts to a single column layout.
2. Complex Layout: Magazine Style
Imagine a magazine page with a large featured article, smaller side articles, and ads:
<div class="grid-container"> <article class="featured">Featured Article</article> <article class="side">Side Article 1</article> <article class="side">Side Article 2</article> <div class="ad">Advertisement</div> <footer class="footer">Footer</footer> </div>
.grid-container { display: grid; grid-template-columns: repeat(3, 1fr); grid-template-areas: "featured featured ad" "side1 side2 ad" "footer footer footer"; gap: 10px; } .featured { grid-area: featured; } .side:nth-child(1) { grid-area: side1; } .side:nth-child(2) { grid-area: side2; } .ad { grid-area: ad; } .footer { grid-area: footer; }
This example uses named grid areas to create a complex, but visually appealing layout.
3. Nested Grids for Component Design
For components within your grid, you might nest grids:
<div class="grid-container"> <div class="card"> <h2 id="Card-Title">Card Title</h2> <div class="card-content"> <p>Content Here</p> <button class="card-button">Action</button> </div> </div> </div>
.grid-container { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; } .card { display: grid; grid-template-columns: 1fr; gap: 10px; } .card-title { /* Styles for title */ } .card-content { display: grid; grid-template-columns: 2fr 1fr; gap: 10px; } .card-button { align-self: flex-start; }
Here, each card itself uses a grid to layout its title and content, demonstrating how grids can be nested for fine control over design elements.
4. Dynamic Grid with Images
For a gallery or portfolio:
<div class="gallery"> <img src="/static/imghwm/default1.png" data-src="img1.jpg" class="lazy" alt="Image 1"> <img src="/static/imghwm/default1.png" data-src="img2.jpg" class="lazy" alt="Image 2"> <img src="/static/imghwm/default1.png" data-src="img3.jpg" class="lazy" alt="Image 3"> <!-- More images --> </div>
.gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px; } .gallery img { width: 100%; height: auto; }
This grid dynamically adjusts to fill the container with images, each at least 200px wide, fitting as many as possible into each row.
Advanced Grid Features
-
Grid Auto-Flow
: Automatically places items. -
Grid Gaps
: Adds space between grid cells. -
Minmax()
: Defines a size range for rows or columns.
Grid Auto-Flow
Grid Auto-Flow
controls how the browser should fill in the grid with items when they are not explicitly placed. By default, items are placed in row-major order, which means items fill across rows before moving to the next row. However, you can change this behavior:-
row
: The default behavior where items are placed in rows before moving to the next column. -
column
: Items are placed in columns before moving to the next row.<script> // Detect dark theme var iframe = document.getElementById('tweet-1832648056296063240-389'); if (document.body.className.includes('dark-theme')) { iframe.src = "https://platform.twitter.com/embed/Tweet.html?id=1832648056296063240&theme=dark" } </script> dense : This option tells the browser to fill in gaps in the grid as items are placed, potentially rearranging items to avoid empty spaces. This can result in an "optimal" arrangement but can also lead to unexpected layouts if not used carefully.
Example:
.grid-container { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-flow: column; /* Items will fill by column before moving to next row */ }
Grid Gaps (or Gutter)
Grid Gaps add space between grid cells, which is crucial for visual breathing room in your layout. You can set gaps for rows, columns, or both:
Example:
.grid-container { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px 40px; /* 20px vertical gap, 40px horizontal gap */ grid-row-gap: 30px; /* Alternative for vertical gap */ grid-column-gap: 50px; /* Alternative for horizontal gap */ }
Using gap is shorthand for both grid-row-gap and grid-column-gap. This feature helps in creating a more polished and organized look, making your content feel less cramped.
Minmax() Function
The Minmax() function in CSS Grid allows you to define a size range for grid tracks (rows or columns). This is extremely useful for creating flexible yet controlled layouts:
Example:
.grid-container { display: grid; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); }
minmax(min, max): Here, min is the minimum width (or height for rows) the track can take, and max is the maximum. The track will grow from min to max as more space becomes available.
auto-fill inside repeat alongside minmax means the browser will automatically generate as many columns as fit within the container, each having a minimum width of 100px but can expand if there's space.
1fr means the track can grow to take up an equal fraction of the available space if there's room after all minimum sizes are accounted for.
Real Example Use:
Imagine designing a dashboard where you want cards to have at least 200px width but grow to fill the space without exceeding 400px:
Solution:
.dashboard { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 400px)); gap: 20px; }
This setup ensures each card is visible and usable on smaller screens while maximizing space on larger displays.
Grid Auto-flow helps in managing how items are naturally placed within your grid, optimizing for space or maintaining order.
Grid Gaps provide the breathing room that makes layouts more visually appealing and user-friendly.
Minmax offers the flexibility to design layouts that adapt beautifully to different screen sizes and content volumes.
Conclusion
I hope by now, you've seen Grid not just as a layout tool, but as a creative companion in your web design adventures. CSS Grid has transformed how we approach layout design, offering a blend of simplicity and power that was hard to imagine before its arrival.
Remember, mastering Grid isn't about memorizing every property or function, but understanding its logic. Like learning any new language, it's about practicetrying out different configurations, seeing how elements respond, and adapting your design to the fluidity of the web.
As you incorporate Grid into your projects, whether they're personal blogs, complex dashboards, or innovative web applications, you'll find yourself equipped to handle challenges with elegance and efficiency. Keep this guide handy, refer back to these examples, and most importantly, keep experimenting.
Thank you for joining me on this exploration of CSS Grid.
? Hello, I'm Eleftheria, Community Manager, developer, public speaker, and content creator.
? If you liked this article, consider sharing it.
? All links | X | LinkedIn
The above is the detailed content of Learn CSS Grid: Simple Guide with Plenty of Examples. For more information, please follow other related articles on the PHP Chinese website!

In a perfect world, our projects would have unlimited resources and time. Our teams would begin coding with well thought out and highly refined UX designs.

Oh, the Many Ways to Make Triangular Breadcrumb Ribbons

SVG has its own set of elements, attributes and properties to the extent that inline SVG code can get long and complex. By leveraging CSS and some of the forthcoming features of the SVG 2 specification, we can reduce that code for cleaner markup.

You might not know this, but JavaScript has stealthily accumulated quite a number of observers in recent times, and Intersection Observer is a part of that

We may not need to throw out all CSS animations. Remember, it’s prefers-reduced-motion, not prefers-no-motion.

PWA (Progressive Web Apps) have been with us for some time now. Yet, each time I try explaining it to clients, the same question pops up: "Will my users be

It's extremely surprising to me that HTML has never had any way to include other HTML files within it. Nor does there seem to be anything on the horizon that

There are a lot of different ways to use SVG. Depending on which way, the tactic for recoloring that SVG in different states or conditions — :hover,


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.