0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CSSを学ぼうシリーズその1(全5回):Gridレイアウト便利だぞ

Last updated at Posted at 2025-05-01
1 / 11

よくあるが実装をミスする要件の1つ

  • エリアの幅:メニューに必要な最小幅を与えて、コンテンツエリアに残り幅を全て与える
    image.png

やってしまいがちな実装方法

  • px や % 指定でがんばる
    最もやってほしくないアンチパターン
    ブラウザの拡大率やウィンドウサイズを変えただけで破綻する
    デザインの変更にも弱い
  • CSSのcalcでがんばる
    px や % と本質は変わらない
    ネックは最適幅
  • JSで幅を測って動的にstyleをあてる
    大袈裟だし、JSの役割って?
    ブラウザの拡大率やウィンドウサイズの変更を考え出すと実装は厄介

CSSの役割・・・とわ?

  • レイアウトや装飾はCSSで実現したいし、そうあるべき

実は素直に実現できる

  • それがGridレイアウト

Gridレイアウトとは

  • 画面をGrid(格子)に割る
  • 縦横の分割サイズを柔軟に指定できる
    image.png

ポイントは「auto」「fr」という単位

  • auto:内容に応じた最適サイズ
  • fr:残ったサイズの割合
  • width: 100vw; と共に使うことが多い

サンプル

.main-grid {
  width: 100vw;
  height: 100vh; /*ヘッダやフッタを固定したいならこれも指定するとよい*/
  display: grid;
  grid-template-columns: auto 1fr;
  grid-template-rows: auto 1fr;
}
.header {
  grid-row: 1 / 2;
  grid-column: 1 / 3;
}
.menu {
  grid-row: 2 / 3;
  grid-column: 1 / 2;
}
.content {
  grid-row: 2 / 3;
  gird-column: 2 / 3;
}

使いどころ

  • 一番外側のレイアウト
  • 静的なレイアウト:必要な領域の数が決まっている

別解:Flowレイアウト

  • Flowレイアウトで似たようなことは出来るらしい
  • が、HTMLタグを入れ子にする必要がない分、Gridレイアウトの方が便利
    試行錯誤しやすく、また変更に強い

最後に

  • 知っているだけで便利に使えます
  • 大事な姿勢:「こう出来たらいいのに」と感じたら生成AIに聞いてみよう
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?