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에 게시됨
검색:318

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]으로 문의하시기 바랍니다. 그것을 삭제하려면
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3