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

Why Learn CSS Grid?

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:

Header
Sidebar
Main
Footer
.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:

Featured Article
Side Article 1
Side Article 2
Advertisement
.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:

Card Title

Content Here

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

\\\"Image \\\"Image \\\"Image
.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

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:

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));}

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.

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

","image":"http://www.luping.net/uploads/20241015/1728973806670e0bee64095.gif","datePublished":"2024-11-08T01:30:44+08:00","dateModified":"2024-11-08T01:30:44+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 学习 CSS 网格:包含大量示例的简单指南

学习 CSS 网格:包含大量示例的简单指南

发布于2024-11-08
浏览:955

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.

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:


Header
Main

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


Side Article 1
Side Article 2
Advertisement
Footer

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


Card Title

Content Here


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






.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

版本声明 本文转载于:https://dev.to/eleftheriabatsou/learn-css-grid-simple-guide-with-plenty-of-examples-31p5?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 使用 Java/ColdFusion/CFML 比较语言检测库(和 API)
    使用 Java/ColdFusion/CFML 比较语言检测库(和 API)
    语言检测是我们在过去的项目中需要的一个功能。 我在 2020 年写了一篇关于 Optimaize Language Detector java 库的 kju2 fork 的使用的文章。 Optimaize 库自 2015 年以来就没有更新过,kju2 分支于 2023 年 4 月 16 日被置于只...
    编程 发布于2024-11-08
  • 如何在 CSS 中在背景上创建曲线?
    如何在 CSS 中在背景上创建曲线?
    在背景上创建曲线在网页开发领域,设计师经常会遇到出于审美目的创建曲线的需要。其中一个场景是将剪切曲线放置在背景顶部,而不是右侧。要实现这一点,需要修改现有的 CSS 代码来调整曲线的位置和形状。操作方法如下:调整伪元素位置:更改伪元素的位置(.box:之前和 .box:after) 到底部:100%...
    编程 发布于2024-11-08
  • 捕获 Django 应用程序中的错误的最佳方法
    捕获 Django 应用程序中的错误的最佳方法
    在 Web 开发的世界中,错误是整个过程中不可避免的一部分。但对于 Django(最流行的 Python Web 框架之一)来说,拥有可靠的错误捕获策略可以在流畅的用户体验和令人沮丧的用户体验之间产生巨大的差异。 作为开发人员,我们经常发现自己不断地与难以捉摸的错误和意外行为作斗争。无论您是构建小...
    编程 发布于2024-11-08
  • 如何将 GORM 字段注释集成到 Protobuf 定义中?
    如何将 GORM 字段注释集成到 Protobuf 定义中?
    将字段注释集成到 Protobuf 定义中寻求在其 protobuf 定义中使用 GORM 提供的字段注释的开发人员可能会因缺少字段注释而遇到挑战Protobuf 3 语法中的本机日期时间类型。为了解决这个问题,可以使用后处理脚本来使用所需的 GORM 注释来增强生成的原型文件。例如,给定以下 pr...
    编程 发布于2024-11-08
  • 开发人员如何构建实时 Web 应用程序?
    开发人员如何构建实时 Web 应用程序?
    在不断发展的技术世界中,实时 Web 应用程序已成为寻求增强用户参与度和简化沟通的企业的强大解决方案。这些应用程序提供即时更新和交互,使其在消息传递、游戏和电子商务等领域至关重要。对于开发人员,特别是那些在澳大利亚开发人员来说,了解构建实时应用程序的细微差别至关重要。本文将探讨创建实时 Web 应用...
    编程 发布于2024-11-08
  • 使用 SAM 框架构建 Go Serverless REST API 并部署到 AWS (Amazon Linux untime)
    使用 SAM 框架构建 Go Serverless REST API 并部署到 AWS (Amazon Linux untime)
    为什么还要另一个 Go 教程 AWS 最近已弃用多项服务和运行时。正如我们所看到的,随着我们喜爱的 CodeCommit 和其他关键服务的终止,AWS Lambda 函数不再支持 Go1.x。 如果您尝试部署大部分过时的教程,您可能会遇到如下错误: Resource creatio...
    编程 发布于2024-11-08
  • C 中的不相交联合
    C 中的不相交联合
    目前还不清楚如何在 C: 中表达此 Haskell 类型 data Tree = Leaf Int | Inner Tree Tree 与 Haskell 和 Rust 等语言不同,C 缺乏对的内置支持 不相交联合。然而,如果我们愿意做一些额外的输入,它确实提供了代表它们所需的所有成分。 首先要认识...
    编程 发布于2024-11-08
  • 社交媒体上的图文帖子有何作用?
    社交媒体上的图文帖子有何作用?
    图形帖子通过提高用户参与度和强化品牌形象在社交媒体营销中发挥着至关重要的作用。在 Instagram、LinkedIn 和 Facebook 等快节奏的社交平台中,用户滚动浏览大量内容,引人注目的视觉效果可以让您的帖子脱颖而出。图形快速有效地传达信息,使其成为与受众沟通的强大工具。 ...
    编程 发布于2024-11-08
  • 如何使用 javac、Ant 或 Maven 递归编译多个 Java 文件?
    如何使用 javac、Ant 或 Maven 递归编译多个 Java 文件?
    如何使用 javac 递归编译所有 Java 文件为每个包使用单独的 shell 命令编译分布在多个包中的大量 Java 文件可能会很乏味包裹。相反,请考虑使用以下方法之一来简化编译。方法 1:使用 @source生成一个文本文件(例如,sources.txt) txt),其中列出了要编译的所有 J...
    编程 发布于2024-11-08
  • 如何使用 Python 在文件的特定位置插入一行?
    如何使用 Python 在文件的特定位置插入一行?
    在Python中的文件中间插入一行在文件中的指定位置插入一行,同时保持文件的完整性现有内容可以使用 Python 的文件处理功能来实现。要在文件中的索引 x 处插入一行,请按照下列步骤操作:打开文件进行读取。使用 readlines() 方法将整个文件读入行列表。使用 insert() 方法在指定索...
    编程 发布于2024-11-08
  • ## 当方法具有指针接收器时,我什么时候应该避免在 Go 中复制实例?
    ## 当方法具有指针接收器时,我什么时候应该避免在 Go 中复制实例?
    复制实例时指针接收器的重要性操作数据时,理解按引用或按值传递值的细微差别至关重要。在 Go 中,方法可以使用值接收器或指针接收器来定义,理解这种选择的含义至关重要,尤其是在复制实例时。值接收器具有值接收器的方法对它们接收到的值的副本进行操作。方法内所做的任何修改都不会影响原始值。这确保了在复制的实例...
    编程 发布于2024-11-08
  • 如何修改不可变 Python 字符串中的单个字符?
    如何修改不可变 Python 字符串中的单个字符?
    错误:'str'对象不支持项目分配Python字符串是不可变的,这意味着一旦创建,它们的单个字符就不能被修改修改的。尝试直接使用项目分配来修改字符(如代码 s2[j] = s1[i] 中所示)会导致错误“TypeError: 'str' 对象不支持项目分配。”此行为与...
    编程 发布于2024-11-08
  • 使用 Java Spring Boot 和 JdbcTemplate 配置 JDBC 以连接到 Databricks
    使用 Java Spring Boot 和 JdbcTemplate 配置 JDBC 以连接到 Databricks
    在软件开发领域,连接到各种数据源是一项基本技能。 Databricks 是一个基于云的数据分析平台,提供了一种处理和分析大量数据的强大方法。在这篇文章中,我们将探讨如何使用 Java 和 Spring 的 JdbcTemplate 配置 JDBC 连接来连接到 Databricks,从而使您能够充分...
    编程 发布于2024-11-08
  • Copilotkit:您的编码冒险人工智能僚机
    Copilotkit:您的编码冒险人工智能僚机
    简介:当人工智能遇见代码(火花四溅) 在不断发展的科技世界中,算法起舞,数据流歌唱,镇上出现了一位新玩家:Copilotkit。这就像有一个非常聪明的朋友,他从不睡觉,不会喝掉你所有的咖啡,也不会因为你凌晨 3 点穿着睡衣编码而评判你。欢迎来到编码的未来,人工智能不仅是辅助,而且是...
    编程 发布于2024-11-08
  • 如何修复 Mac 上的 Java 8 安装问题
    如何修复 Mac 上的 Java 8 安装问题
    解决 Mac 上 Java 8 的安装问题您关于 Mac 上 Java 8 安装文件的意外位置和兼容性挑战的查询重点开发商面临的共同问题。本文旨在提供一个全面的解决方案来解决这些问题。安装异常Oracle的Java安装程序倾向于将Java 8文件放在/Library/Java/JavaVirtual...
    编程 发布于2024-11-08

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3