3
3

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 3 years have passed since last update.

css のレイアウト系のメモ (随時更新)

Last updated at Posted at 2022-01-24

概要

FlexBox や Grid layout など、実装する際に毎回迷うのでテンプレとして元になるコードを列挙しておく。

中央寄せ

<div style="height: 200px; display: flex; align-items: center; justify-content: center;">
  <div style="width: 100px; height: 100px">中央寄せ</div>
</div>

image.png

画面いっぱい

<style>
.layout-max-screen {
  box-sizing: border-box;  /* これがないと padding 分はみ出てしまう */
  border: none;  /* border 分ははみ出るので注意 */
  height: 100vh;
  padding: 10px;  /* padding 要らないなら不要 */
  display: grid;  /* これにより子の div も画面いっぱいに広がる */
}
</style>

<div class="layout-max-screen">
  <div>画面いっぱい</div>
</div>

image.png

画面のレイアウトの一部が可変

レイアウトが完全固定なら Grid 使えばよいが、可変でアニメもする場合は FlexBox で実装する必要あり。

<div>
  <div style="display: flex; flex-wrap: nowrap; gap: 10px; justify-content: flex-start; align-items: stretch;">
    <div style="width: 80px;">a</div>
    <div style="width: 80px;">b</div>
    <div style="flex: 1;">c</div>
  </div>
</div>

image.png

前述と組み合わせれば、高さ方向で画面MAXになる。

<div class="layout-max-screen">
  <div style="display: flex; flex-wrap: nowrap; gap: 10px; justify-content: flex-start; align-items: stretch;">
    <div style="width: 80px;">a</div>
    <div style="width: 80px;">b</div>
    <div style="flex: 1;">c</div>
  </div>
</div>

image.png

Grid Layout

<div class="layout-max-screen">
  <div style="
    display: grid;
    grid-gap: 10px;
    grid-template-columns: 80px 80px 1fr;
    grid-template-rows: 40px 1fr;
    grid-template-areas: 'left  center  header'  'left  center  main';
  ">
    <div style="grid-area: left;">left</div>
    <div style="grid-area: center;">center</div>
    <div style="grid-area: header;">header</div>
    <div style="grid-area: main;">main</div>
  </div>
</div>

image.png

  • grid-template-areas: 'left center header' 'left center main'; は改行すると認識しなくなるので注意。(Vue3 にて確認。) Vue3 なら、下記のようにするのがよい。

    :style="{
      gridTemplateAreas: `
        'left  center  header'
        'left  center  main'
      `
    }"
    
3
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?