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
浏览:736

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]删除
最新教程 更多>
  • 如何使用“ JSON”软件包解析JSON阵列?
    如何使用“ JSON”软件包解析JSON阵列?
    parsing JSON与JSON软件包 QUALDALS:考虑以下go代码:字符串 } func main(){ datajson:=`[“ 1”,“ 2”,“ 3”]`` arr:= jsontype {} 摘要:= = json.unmarshal([] byte(...
    编程 发布于2025-04-11
  • 如何使用Python的请求和假用户代理绕过网站块?
    如何使用Python的请求和假用户代理绕过网站块?
    如何使用Python的请求模拟浏览器行为,以及伪造的用户代理提供了一个用户 - 代理标头一个有效方法是提供有效的用户式header,以提供有效的用户 - 设置,该标题可以通过browser和Acterner Systems the equestersystermery和操作系统。通过模仿像Chro...
    编程 发布于2025-04-11
  • 您可以使用CSS在Chrome和Firefox中染色控制台输出吗?
    您可以使用CSS在Chrome和Firefox中染色控制台输出吗?
    在javascript console 中显示颜色是可以使用chrome的控制台显示彩色文本,例如红色的redors,for for for for错误消息?回答是的,可以使用CSS将颜色添加到Chrome和Firefox中的控制台显示的消息(版本31或更高版本)中。要实现这一目标,请使用以下模...
    编程 发布于2025-04-11
  • 如何有效地转换PHP中的时区?
    如何有效地转换PHP中的时区?
    在PHP 利用dateTime对象和functions DateTime对象及其相应的功能别名为时区转换提供方便的方法。例如: //定义用户的时区 date_default_timezone_set('欧洲/伦敦'); //创建DateTime对象 $ dateTime = ne...
    编程 发布于2025-04-11
  • 在Ubuntu/linux上安装mysql-python时,如何修复\“ mysql_config \”错误?
    在Ubuntu/linux上安装mysql-python时,如何修复\“ mysql_config \”错误?
    mysql-python安装错误:“ mysql_config找不到”“ 由于缺少MySQL开发库而出现此错误。解决此问题,建议在Ubuntu上使用该分发的存储库。使用以下命令安装Python-MysqldB: sudo apt-get安装python-mysqldb sudo pip in...
    编程 发布于2025-04-11
  • 如何从Python中的字符串中删除表情符号:固定常见错误的初学者指南?
    如何从Python中的字符串中删除表情符号:固定常见错误的初学者指南?
    从python import codecs import codecs import codecs 导入 text = codecs.decode('这狗\ u0001f602'.encode('utf-8'),'utf-8') 印刷(文字)#带有...
    编程 发布于2025-04-11
  • 如何干净地删除匿名JavaScript事件处理程序?
    如何干净地删除匿名JavaScript事件处理程序?
    删除匿名事件侦听器将匿名事件侦听器添加到元素中会提供灵活性和简单性,但是当要删除它们时,可以构成挑战,而无需替换元素本身就可以替换一个问题。 element? element.addeventlistener(event,function(){/在这里工作/},false); 要解决此问题,请考虑...
    编程 发布于2025-04-11
  • 版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    在时间戳列上使用current_timestamp或MySQL版本中的current_timestamp或在5.6.5 此限制源于遗留实现的关注,这些限制需要对当前的_timestamp功能进行特定的实现。 创建表`foo`( `Productid` int(10)unsigned not n...
    编程 发布于2025-04-11
  • 为什么PHP的DateTime :: Modify('+1个月')会产生意外的结果?
    为什么PHP的DateTime :: Modify('+1个月')会产生意外的结果?
    使用php dateTime修改月份:发现预期的行为在使用PHP的DateTime类时,添加或减去几个月可能并不总是会产生预期的结果。正如文档所警告的那样,“当心”这些操作的“不像看起来那样直观。 考虑文档中给出的示例:这是内部发生的事情: 现在在3月3日添加另一个月,因为2月在2001年只有2...
    编程 发布于2025-04-11
  • 如何限制动态大小的父元素中元素的滚动范围?
    如何限制动态大小的父元素中元素的滚动范围?
    在交互式接口中实现垂直滚动元素的CSS高度限制,控制元素的滚动行为对于确保用户体验和可访问性是必不可少的。一种这样的方案涉及限制动态大小的父元素中元素的滚动范围。问题:考虑一个布局,其中我们具有与用户垂直滚动一起移动的可滚动地图div,同时与固定的固定sidebar保持一致。但是,地图的滚动无限期...
    编程 发布于2025-04-11
  • 如何解决由于Android的内容安全策略而拒绝加载脚本... \”错误?
    如何解决由于Android的内容安全策略而拒绝加载脚本... \”错误?
    Unveiling the Mystery: Content Security Policy Directive ErrorsEncountering the enigmatic error "Refused to load the script..." when deployi...
    编程 发布于2025-04-11
  • 在程序退出之前,我需要在C ++中明确删除堆的堆分配吗?
    在程序退出之前,我需要在C ++中明确删除堆的堆分配吗?
    在C中的显式删除 在C中的动态内存分配时,开发人员通常会想知道是否有必要在heap-procal extrable exit exit上进行手动调用“ delete”操作员,但开发人员通常会想知道是否需要手动调用“ delete”操作员。本文深入研究了这个主题。 在C主函数中,使用了动态分配变量(H...
    编程 发布于2025-04-11
  • 如何检查对象是否具有Python中的特定属性?
    如何检查对象是否具有Python中的特定属性?
    方法来确定对象属性存在寻求一种方法来验证对象中特定属性的存在。考虑以下示例,其中尝试访问不确定属性会引起错误: >>> a = someClass() >>> A.property Trackback(最近的最新电话): 文件“ ”,第1行, AttributeError: SomeClass...
    编程 发布于2025-04-11
  • 如何在GO编译器中自定义编译优化?
    如何在GO编译器中自定义编译优化?
    在GO编译器中自定义编译优化 GO中的默认编译过程遵循特定的优化策略。 However, users may need to adjust these optimizations for specific requirements.Optimization Control in Go Compi...
    编程 发布于2025-04-11
  • 如何使用不同数量列的联合数据库表?
    如何使用不同数量列的联合数据库表?
    合并列数不同的表 当尝试合并列数不同的数据库表时,可能会遇到挑战。一种直接的方法是在列数较少的表中,为缺失的列追加空值。 例如,考虑两个表,表 A 和表 B,其中表 A 的列数多于表 B。为了合并这些表,同时处理表 B 中缺失的列,请按照以下步骤操作: 确定表 B 中缺失的列,并将它们添加到表的末...
    编程 发布于2025-04-11

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

Copyright© 2022 湘ICP备2022001581号-3