0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

gridレイアウトの基礎知識と活用法

Posted at

はじめに

学んだことを忘れないように備忘録として残しています

gridレイアウトとは

CSSで提供されるレイアウトシステムの一つで、レイアウトを効率的に作成するためのものです。
gridレイアウトは親要素(コンテナ)と子要素(アイテム)の関係で構成されます。

【gridコンテナ】
gridレイアウトを適用する要素

display: grid;を指定します。

【gridアイテム】
gridコンテナの直接の子要素が対象となります。

主要なプロパティ

grid-template-rows / grid-template-columns

行と列のサイズを定義します。(rows,columnsと複数系なので要注意!)

 .container {
    display: grid;
    
    grid-template-columns: 100px 200px auto;
    
    grid-template-rows: 50px auto; 
}

grid-template

行と列のサイズを一括指定します。
例)grid-template: rowの値 rowの値 / columnsの値 columnsの値;

    .container {
        display: grid;
        
        grid-template:  50px auto / 100px 200px auto;
    }

単位fr(エフアール)

frとは、CSSのグリッドレイアウトで使用する単位。
フラクションの略で日本語だと、分数という意味。

グリッドコンテナー内の利用可能な空間の割合を表します。
例えば、3行の中身の幅を 1:1:1 にしたい場合は下記のように指定します。

    .container {
        display: grid;
        grid-template-columns:  1fr 1fr 1fr;
    }

pxなどの固定幅と組み合わせることも可能です!

grid itemの配置方法

デフォルト配置

グリッドアイテムは通常、コンテナ内のグリッドラインに沿って左上から順に配置されます。
しかし、**grid-area;**を活用することで、画面幅やデバイスによって配置を変えたいなど、作成したアイテムに名前をつけて自由に配置することができます。

gri-areaで自由配置

例)ヘッダー、フッター付きの2カラムレイアウトを組む

【使用手順】
1.コンテナにグリッドエリアを定義

行(row)と列(column)のサイズも同時に設定できます。

ヘッダー (header) が全幅を占有。
サイドバー (sidebar) とメインコンテンツ (main) が左右に分割。
フッター (footer) が全幅を占有。

.container {
    display: grid;
    grid-template-areas: 
        "header header"
        "sidebar main"
        "footer footer";
    grid-template-rows: 100px 1fr 100px; /* 行の高さ */
    grid-template-columns: 200px 1fr; /* 列の幅 */
}

②アイテムとエリアの紐付けをする

.header {
    grid-area: header;
}
.sidebar {
    grid-area: sidebar;
}
.main {
    grid-area: main;
}
.footer {
    grid-area: footer;
}

gridレイアウトとFlexbox

【Flexboxが適している場合】
1次元のレイアウト(行または列のどちらか一方向)

  • 例:ナビゲーションバー、ボタンの横並び
  • 要素サイズが可変で、順番が重要な場合

【gridが適している場合】
2次元のレイアウト(行と列を組み合わせた複雑な配置)

  • 例:ウェブページ全体の構造、ダッシュボード
  • レイアウトが複雑で、特定のアイテムを指定位置に配置したい場合

単純な並びや1方向ならFlexbox。
複雑なレイアウトや2次元構成ならGridが最適。

まとめ

gridレイアウトは、ウェブページの効率的な2次元構造を実現する強力なCSSツールです。
一方、Flexboxは1次元レイアウトに適しており、それぞれの特性を理解して使い分けることが重要です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?