웹 프론트엔드 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 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 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

정적 양식 공급자의 비교 정적 양식 공급자의 비교 Apr 16, 2025 am 11:20 AM

"정적 양식 공급자"라는 용어를 동전하려고합시다. 당신은 당신의 HTML을 가져옵니다

Sass를 더 빨리 만들기위한 개념 증명 Sass를 더 빨리 만들기위한 개념 증명 Apr 16, 2025 am 10:38 AM

새로운 프로젝트가 시작될 때, Sass 컴파일은 눈을 깜박이게합니다. 특히 BrowserSync와 짝을 이루는 경우 기분이 좋습니다.

주간 플랫폼 뉴스 : HTML로드 속성, 주요 ARIA 사양 및 iframe에서 Shadow Dom으로 이동 주간 플랫폼 뉴스 : HTML로드 속성, 주요 ARIA 사양 및 iframe에서 Shadow Dom으로 이동 Apr 17, 2025 am 10:55 AM

이번 주에 플랫폼 뉴스 라운드 업 RONDUP, Chrome은로드에 대한 새로운 속성, 웹 개발자를위한 접근성 사양 및 BBC Move를 소개합니다.

HTML 대화 요소와 함께 일부 실습 HTML 대화 요소와 함께 일부 실습 Apr 16, 2025 am 11:33 AM

이것은 처음으로 HTML 요소를보고 있습니다. 나는 그것을 잠시 동안 알고 있었지만 아직 스핀을 위해 그것을 가져 갔다. 그것은 꽤 시원하고 있습니다

PaperForm PaperForm Apr 16, 2025 am 11:24 AM

구매 또는 빌드는 기술 분야의 고전적인 논쟁입니다. 신용 카드 청구서에 라인 항목이 없기 때문에 물건을 구축하는 것이 저렴할 수 있지만

주간 플랫폼 뉴스 : 텍스트 간격 북마크, 최상위 차단, 새로운 앰프 로딩 표시기 주간 플랫폼 뉴스 : 텍스트 간격 북마크, 최상위 차단, 새로운 앰프 로딩 표시기 Apr 17, 2025 am 11:26 AM

이번 주에 타이포그래피를 검사하기위한 편리한 북마크 인 Roundup, JavaScript 모듈과 Facebook의 Facebook 등을 어떻게 가져 오는지 땜질하기 위해 대기하는 편리한 북마크 인 Roundup과 Facebook의

'Podcast 구독'링크는 어디에서 링크해야합니까? 'Podcast 구독'링크는 어디에서 링크해야합니까? Apr 16, 2025 pm 12:04 PM

한동안 iTunes는 팟 캐스팅에서 큰 개 였으므로 "Podcast 구독"을 링크 한 경우 다음과 같습니다.

직접 비자 스크립트 기반 분석을 호스팅하는 옵션 직접 비자 스크립트 기반 분석을 호스팅하는 옵션 Apr 15, 2025 am 11:09 AM

사이트에서 방문자 및 사용 데이터를 추적하는 데 도움이되는 분석 플랫폼이 많이 있습니다. 아마도 널리 사용되는 Google 웹 로그 분석

See all articles