首頁 > web前端 > css教學 > 主體

學習 CSS 網格:帶有大量範例的簡單指南

Barbara Streisand
發布: 2024-10-05 06:16:30
原創
868 人瀏覽過

嘿那裡!如果您曾經覺得 CSS 網格有點像試圖蒙住眼睛解開魔術方塊,那麼您並不孤單。我是 Eleftheria,今天我來這裡是為了幫助您輕鬆瀏覽 CSS 網格。讓我們深入了解。 ?

CSS 網格簡介

CSS 網格的目的是讓您能夠創建複雜的二維佈局,而這在以前是非常令人頭疼的。在 Grid 出現之前,我們一直在使用浮動、表格或 Flexbox 進行佈局。 Grid 出現並說:“別喝啤酒”,它提供了一種更直觀、更強大的網頁結構方式。

Learn CSS Grid: Simple Guide with Plenty of Examples

為什麼要學 CSS 網格?

  • 效率

    :網格簡化了設計佈局的方式,減少了僅用於佈局目的的嵌套元素的需求。
  • 靈活性

    :它非常適合響應式設計,可以完美適應不同的螢幕尺寸。
  • 強大

    :使用網格,您可以輕鬆地垂直和水平對齊元素,這對舊方法來說是一場噩夢。

CSS 網格基礎

讓我們從頭開始。要使用 CSS Grid,您需要將容器定義為網格。例如:

.container { display: grid;}


登入後複製

這個簡單的程式碼將 .container 變成了網格容器,這意味著它的直接子級將成為網格項。

建立網格列和行

您可以透過指定列和行來定義網格結構:

.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 */
}



登入後複製

這裡,1fr 表示可用空間的一小部分,使列寬度相等。

將物品放置在網格中

您可以使用 grid-column 和 grid-row 屬性將項目放置在特定區域:

.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 */
}



登入後複製

這會將 .item-a 從第一列行開始放置到第三列,並穿過第一行。

網格線和區域

您可以命名線路以便於參考:

.grid-container {
    grid-template-columns: [start] 1fr [line2] 1fr [end];
    grid-template-rows: [row1-start] auto [row2-start] auto [row3-end];
}


登入後複製

然後使用這些名稱:

.item-b {
    grid-column: start / line2;
    grid-row: row1-start / row2-start;
}


登入後複製

網格區域

為了更直覺的方法,您可以命名區域:

.grid-container {
    display: grid;
    grid-template-areas:
    "header header header"
    "sidebar main main"
    "footer footer footer";
}


登入後複製

然後將元素分配給這些區域:

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


登入後複製

更多 CSS 網格實際應用範例

1。帶有媒體查詢的響應式佈局

CSS 網格的優點之一是它易於處理響應式設計。這是一個範例,展示如何針對不同的螢幕尺寸

調整網格佈局:

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


登入後複製

此設定建立一個網格,其中每個項目的寬度至少為 300 像素,但會不斷增長以佔用可用空間。在小於 768px 的螢幕上,它會轉換為單列佈局。

2。複雜版面:雜誌風格

想像一個雜誌頁面,其中有一篇大的特色文章、較小的副文章和廣告:

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


登入後複製

此範例使用命名網格區域來建立複雜但具有視覺吸引力的佈局。

3。用於組件設計的巢狀網格

對於網格內的元件,您可以巢狀網格:

<div class="grid-container">
    <div class="card">
        <h2 class="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;
}


登入後複製

這裡,每張卡片本身都使用網格來佈局其標題和內容,演示瞭如何嵌套網格以對設計元素進行精細控制。

4。帶有影像的動態網格

對於畫廊或作品集:

<div class="gallery">
    <img src="img1.jpg" alt="Image 1">
    <img src="img2.jpg" alt="Image 2">
    <img src="img3.jpg" 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;
}


登入後複製

此網格動態調整以用圖像填充容器,每個圖像至少 200 像素寬,每行容納盡可能多的圖像。

進階網格功能

  • 網格自動流動

    :自動放置項目。
  • 網格間隙

    :在網格單元之間增加空間。
  • Minmax()

    :定義行或列的大小範圍。

網格自動流動

網格自動流

控制瀏覽器在未明確放置項目時應如何用項目填滿網格。預設情況下,項目按行優先順序放置,這表示項目在移動到下一行之前會跨行填充。但是,您可以更改此行為:
  • 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

以上是學習 CSS 網格:帶有大量範例的簡單指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!