1
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?

CSS Gridで左右カラムの高さが勝手に揃う問題

1
Posted at

問題のコード

const container = css({
  display: "grid",
  gridTemplateColumns: "1fr 1fr",
  gap: "16px",
});

const Layout = () => {
  return (
    <div className={container}>
      <div style={{ background: "#ccc" }}>
        左のコンテンツ
      </div>

      <div style={{ background: "#eee", height: "500px" }}>
        右のコンテンツ(高さが大きい)
      </div>
    </div>
  );
};

この場合、右側を500pxにすると、左側も同じ高さまで伸びます。

原因:align-items のデフォルトが stretch

CSS Gridでは、以下のデフォルト値が設定されています。

プロパティ デフォルト値 役割
align-items stretch 縦方向の配置
justify-items stretch 横方向の配置

つまり、特に何も指定しないとこうなります。

.container {
  display: grid;
  align-items: stretch;
}

なぜ高さが揃うのか

align-items: stretch が有効な状態では、

  • 各アイテムは「グリッドセルいっぱい」に広がる
  • 行の高さは「一番高い要素」に合わせて決まる
  • 他の要素もその高さに引き伸ばされる

今回のケースだと:

  1. 右側が500pxになる
  2. 行の高さも500pxになる
  3. 左側も500pxまで引き伸ばされる

という流れです。

解決方法

高さをそれぞれ独立させたい場合は、align-items を変更します。

const container = css({
  display: "grid",
  gridTemplateColumns: "1fr 1fr",
  gap: "16px",

  alignItems: "start", // これを追加
});

修正後の挙動

const Layout = () => {
  return (
    <div className={container}>
      <div style={{ background: "#ccc" }}>
        左のコンテンツ(高さは中身分)
      </div>

      <div style={{ background: "#eee", height: "500px" }}>
        右のコンテンツ(高さ500px)
      </div>
    </div>
  );
};

これで、

  • 左:コンテンツ分の高さ
  • 右:500px

と、独立した高さになります。

align-items の値の違い

挙動
stretch(デフォルト) 高い要素に合わせて引き伸ばされる
start 上揃え。高さは独立
center 縦中央に配置
end 下揃え

今回のようなケースでは start が適しています。

justify-items についても同じ

横方向にも同様の仕組みがあります。

justify-items: stretch; // デフォルト

つまり、

  • 縦:align-items
  • 横:justify-items

両方ともデフォルトで伸びる設定になっています。

中央寄せしたい場合はこう書けます。

place-items: center;

これは以下の省略形です。

align-items: center;
justify-items: center;
1
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
1
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?