ホームページ ウェブフロントエンド CSSチュートリアル CSS グリッドを学ぶ: 豊富な例を含むシンプルなガイド

CSS グリッドを学ぶ: 豊富な例を含むシンプルなガイド

Oct 05, 2024 am 06:16 AM

こんにちは! CSS グリッドは目隠しをしてルービック キューブを解こうとしているようなものだと感じたことがあるのは、あなただけではありません。私は Eleftheria です。今日は、CSS グリッドを簡単に操作できるようにお手伝いします。それでは、詳しく見ていきましょう。 ?

CSS グリッドの概要

CSS グリッドは、以前は実現するのが大変だった複雑な 2 次元レイアウトを作成できるようにするために作られています。 Grid が登場する前は、フロート、テーブル、またはフレックスボックスを使ってレイアウトを調整していました。 Grid は、「ビールを待ってください」と言い、Web ページを構造化するためのより直感的で強力な方法を提供しました。

Learn CSS Grid: Simple Guide with Plenty of Examples

CSS グリッドを学ぶ理由

  • 効率

    : グリッドを使用すると、レイアウトの設計方法が簡素化され、レイアウト目的のためだけにネストされた要素の必要性が減ります。
  • 柔軟性

    : レスポンシブ デザインに最適で、さまざまな画面サイズに美しく適応します。
  • パワー

    : Grid を使用すると、要素を垂直方向と水平方向の両方に簡単に整列させることができます。これは、古い方法では悪夢でした。

CSS グリッドの基本

一番最初から始めましょう。 CSS グリッドを使用するには、コンテナをグリッドとして定義する必要があります。例:

.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 は利用可能なスペースの 1 分の 1 を意味し、列の幅が等しくなります。

グリッドにアイテムを配置する

グリッド列プロパティとグリッド行プロパティを使用して、特定の領域に項目を配置できます。

.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 が最初の列行から 3 行目、そして最初の行まで配置されます。

グリッド線と領域

参照しやすいように行に名前を付けることができます:

.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 グリッドの長所の 1 つは、レスポンシブ デザインの取り扱いが容易であることです。 さまざまな画面サイズ

に合わせてグリッド レイアウトを調整する方法を示す例を次に示します。

.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()

    : 行または列のサイズ範囲を定義します。

グリッド自動フロー

Grid Auto-Flow

は、項目が明示的に配置されていない場合に、ブラウザーが項目をグリッドにどのように埋めるかを制御します。デフォルトでは、項目は行優先の順序で配置されます。つまり、項目は次の行に移動する前に行全体に配置されます。ただし、この動作は変更できます:
  • row

    : 次の列に移動する前に項目が行に配置されるデフォルトの動作。
  • column

    : 項目は次の行に移動する前に列に配置されます。<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 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

それは&#039; Vueチームにそれを成し遂げてくれておめでとうございます。それは大規模な努力であり、長い時間がかかったことを知っています。すべての新しいドキュメントも同様です。

Redwood.jsと動物相を使用してイーサリアムアプリを構築します Redwood.jsと動物相を使用してイーサリアムアプリを構築します Mar 28, 2025 am 09:18 AM

最近のビットコインの価格が20k $ $ USDを超えており、最近30Kを破ったので、イーサリアムを作成するために深く掘り下げる価値があると思いました

ブラウザから有効なCSSプロパティ値を取得できますか? ブラウザから有効なCSSプロパティ値を取得できますか? Apr 02, 2025 pm 06:17 PM

私はこの非常に正当な質問で誰かに書いてもらいました。 Leaは、ブラウザから有効なCSSプロパティ自体を取得する方法についてブログを書いています。それはこのようなものです。

粘着性のあるポジショニングとサスのダッシュを備えた積み重ねられたカード 粘着性のあるポジショニングとサスのダッシュを備えた積み重ねられたカード Apr 03, 2025 am 10:30 AM

先日、Corey Ginnivanのウェブサイトから、この特に素敵なビットを見つけました。そこでは、スクロール中にカードのコレクションが互いに積み重ねられていました。

CI/CDで少し CI/CDで少し Apr 02, 2025 pm 06:21 PM

「ウェブサイト」は「モバイルアプリ」よりも適していると言いますが、Max Lynchからのこのフレーミングが好きです。

レスポンシブデザインのブラウザを比較します レスポンシブデザインのブラウザを比較します Apr 02, 2025 pm 06:25 PM

これらのデスクトップアプリがいくつかあり、目標があなたのサイトをさまざまな次元ですべて同時に表示しています。たとえば、書くことができます

WordPressブロックエディターでのマークダウンとローカリゼーションを使用します WordPressブロックエディターでのマークダウンとローカリゼーションを使用します Apr 02, 2025 am 04:27 AM

WordPressエディターでユーザーに直接ドキュメントを表示する必要がある場合、それを行うための最良の方法は何ですか?

フレックスレイアウト内の紫色のスラッシュ領域が誤って「オーバーフロー空間」と見なされるのはなぜですか? フレックスレイアウト内の紫色のスラッシュ領域が誤って「オーバーフロー空間」と見なされるのはなぜですか? Apr 05, 2025 pm 05:51 PM

フレックスレイアウトの紫色のスラッシュ領域に関する質問フレックスレイアウトを使用すると、開発者ツールなどの混乱する現象に遭遇する可能性があります(D ...

See all articles