搜索
首页web前端css教程学习 CSS 网格:带有大量示例的简单指南

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. ?

<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>

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.

Learn CSS Grid: Simple Guide with Plenty of Examples

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.

  • 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

以上是学习 CSS 网格:带有大量示例的简单指南的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
光标的下一个CSS样式光标的下一个CSS样式Apr 23, 2025 am 11:04 AM

具有CSS的自定义光标很棒,但是我们可以将JavaScript提升到一个新的水平。使用JavaScript,我们可以在光标状态之间过渡,将动态文本放置在光标中,应用复杂的动画并应用过滤器。

世界碰撞:使用样式查询的钥匙帧碰撞检测世界碰撞:使用样式查询的钥匙帧碰撞检测Apr 23, 2025 am 10:42 AM

互动CSS动画和元素相互启动的元素在2025年似乎更合理。虽然不需要在CSS中实施乒乓球,但CSS的灵活性和力量的增加,可以怀疑Lee&Aver Lee&Aver Lee有一天将是一场

使用CSS背景过滤器进行UI效果使用CSS背景过滤器进行UI效果Apr 23, 2025 am 10:20 AM

有关利用CSS背景滤波器属性来样式用户界面的提示和技巧。您将学习如何在多个元素之间进行背景过滤器,并将它们与其他CSS图形效果集成在一起以创建精心设计的设计。

微笑吗?微笑吗?Apr 23, 2025 am 09:57 AM

好吧,事实证明,SVG的内置动画功能从未按计划进行弃用。当然,CSS和JavaScript具有承载负载的能力,但是很高兴知道Smil并没有像以前那样死在水中

'漂亮”在情人眼中'漂亮”在情人眼中Apr 23, 2025 am 09:40 AM

是的,让#039;跳上文字包装:Safari Technology Preview In Pretty Landing!但是请注意,它与在铬浏览器中的工作方式不同。

CSS-tricks编年史XLIIICSS-tricks编年史XLIIIApr 23, 2025 am 09:35 AM

此CSS-tricks更新了,重点介绍了年鉴,最近的播客出现,新的CSS计数器指南以及增加了几位新作者,这些新作者贡献了有价值的内容。

tailwind的@Apply功能比听起来更好tailwind的@Apply功能比听起来更好Apr 23, 2025 am 09:23 AM

在大多数情况下,人们展示了@Apply的@Apply功能,其中包括Tailwind的单个property实用程序之一(会改变单个CSS声明)。当以这种方式展示时,@Apply听起来似乎很有希望。如此明显

感觉就像我没有释放:走向理智的旅程感觉就像我没有释放:走向理智的旅程Apr 23, 2025 am 09:19 AM

像白痴一样部署的部署归结为您部署的工具与降低复杂性与添加的复杂性之间的奖励之间的不匹配。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中