3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【CSS Grid 応用編】位置と大きさの指定/auto-fillとauto-fit

Posted at

前回(【CSS Grid 基本編】grid-template-columns/rows、gapについて - Qiita)は CSS grid の基本的な使い方をまとめたので今回は応用編。

位置と大きさを指定するgrid-template-areasgrid-area

例えば、簡単にWEBサイトでよく見るようなレイアウトがgridで簡単に組める。

image.png
親と子に指定する必要があり、

  • 子にgrid-areasで名前を指定してあげる。
  • 親のgrid-template-areasで子に指定したgrid-areasの名前で位置と大きさを決める。

子にgrid-areasで名前を指定してあげる。

HTML
<div class="wrapper">
  <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;
}

親にgrid-template-areasを指定

grid-template-columns-rowsで列と行を決め、
grid-template-areas を指定。

(今回は横3×縦4の均等なグリッドで説明)
image.png

grid-template-areas
  grid-template-areas:
    "header header header"
    "sidebar main main"
    "sidebar main main"    
    "footer footer footer";

grid-template-areas""内を1行として、スペースを開けて列の指定する。
絵と同じ見た目でかけるからかなり感覚的に指定できる。

CODEPEN

See the Pen Untitled by himeka223 (@himeka223) on CodePen.

auto-fitauto-fillminimaxの組み合わせで簡単にレスポンシブ、折返しができる!

image.png

auto-fit
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
auto-fill
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));

上はどちらも 100px~1fr に伸縮する指定。
縮めなくなったら(100px以下)、段落ち。
repeat()で繰り返す回数ではなくauto-fitauto-fillを指定することで自動で判断してくれる。

  • auto-fitは子の数分のグリッドができるので横幅いっぱいに見える
  • auto-fillは子の幅を基準にグリッドができ、余るグリッドができる

CODEPEN

See the Pen Grid/auto-fit,-fill by himeka223 (@himeka223) on CodePen.

まとめ

他にもgridの指定は色々ありそうだけど、この辺を押さえておけば使いこなせそう

参考サイト

これは便利!CSS Gridのauto-fillとauto-fitの使い分けでRWDが捗る – WPJ
2021年版、CSS Gridでどのように配置されるかをまとめたチートシート
gridレイアウトについて調べました【CSS/grid-template/auto-fit/auto-fill】 | えむ家のメモ帳

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?