【CSS】overflowの概要と具体例

overflowプロパティについて

overflowとは要素からはみ出したコンテンツの扱いを記述するプロパティです。overflowoverflow-xプロパティとoverflow-yプロパティを一括指定します。

overflow-xは水平方向に、overflow-yは垂直方向にはみ出したコンテンツの扱いを記述するプロパティです。

overflowで指定できる値と意味

overflowで指定できる主な値と意味の対応は以下の通りです。

意味
visibleはみ出したコンテンツを表示
hiddenはみ出したコンテンツを非表示
scrollはみ出したコンテンツはスクロールで表示
autoユーザーヘージェントに依存

overflowで指定できる値の一覧はMDN Web Docs『overflow』をご覧ください。

overflowの使い方

コンテンツが配置される要素に対してoverflowプロパティを追加します。

overflowの具体例

以下は、コンテンツがはみ出している要素の例です。

See the Pen without-overflow by Toshiharu Nishina (@nishina555) on CodePen.

上記の要素にoverflowを適用した結果について紹介します。

overflow: visible

See the Pen overflow-visible by Toshiharu Nishina (@nishina555) on CodePen.

overflow: hidden

See the Pen overflow-hidden by Toshiharu Nishina (@nishina555) on CodePen.

overflow: scroll

See the Pen overflow-scroll by Toshiharu Nishina (@nishina555) on CodePen.

overflow: auto

See the Pen overflow-auto by Toshiharu Nishina (@nishina555) on CodePen.

overflowの応用例

横スクロール可能な横並びアイテム

横並びアイテムの親要素にdisplya: flexoverflow-x: scrollを追加することで横スクロールを実装できます。具体例は以下の通りです。

<div class="wrapper">
  <div class="container">
    <div class="container__item">item</div>
    <div class="container__item">item</div>
    <div class="container__item">item</div>
    <div class="container__item">item</div>
  </div>
</div>
.wrapper {
  display: flex;
  overflow-x: scroll;
  background: lightgreen;
}

.container {
  display: flex;
  border: dotted;
}

.container__item {
  width: 200px;
  height: 200px;
  background: lightblue;
}

.container__item:not(:last-child) {
  margin-right: 10px;
}

See the Pen scroll-line-items-after by Toshiharu Nishina (@nishina555) on CodePen.

横スクロール可能な横並びアイテムの実装については[【CSS】overflowとFlexboxで横スクロール可能な横並びアイテムを実装する](/scroll-flex-overflow/)でも紹介しています。

さいごに

Twitter(@nishina555)やってます。フォローしてもらえるとうれしいです!

参考資料

タグ: css