0
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と擬似要素を使って画像と背景をずらして重ねる方法

Last updated at Posted at 2025-04-05

はじめに

この記事では、CSSと擬似要素を使って画像と背景をずらして重ねる方法をまとめる。

実現したいこと

  • 下記画像のレイアウトを実現したい1

Image from Gyazo

前提

  • イチゴが書かれている薄ピンクの部分は画像
  • 背景色が異なる部分は画像ではない
  • 画像とテキストは横並び

試したこと

背景色が異なる部分には、CSSの擬似要素を用いた。また、背景色が異なる部分と画像を重ねるため、CSSにおいてpositionプロパティを下記のように用いた。

index.html
<div class="overlap">
    <img src="strayberry.jpg">
    <div class="text">
      <h2>新発売</h2>
      <p>今週発売の新商品!いちご味のチョコレートです。</p>
    </div>
  </div>
style.css
.overlap {
  display: flex;
  height: 500px;
}

/* 画像 */
img {
  width: 400px;
  height: 400px;
  position: relative; /* 重ねられる要素にposition: relative;を指定 */
  z-index: 1; /* 前面に配置 */
  left: 400px;
  margin-top: 30px;
}

/* テキスト */
.text {
  position: relative; /* 重ねられる要素にposition: relative;を指定 */
  z-index: 1; /* 前面に配置 */
  color: brown;
  left: 300px;
  font-size: 26px;
  padding-left: 130px;
}

/* 背景色が異なる部分 */
.overlap::after {
  content: "";
  width: 50%;
  height: 410px;
  background-color: brown;
  position: absolute; /* 重ねる要素にposition: absolute;を指定 */
  z-index: 0; /* 最背面に配置 */
  margin-top: 50px;
}

結果・考えたこと

上記のコードで、実現したかったレイアウトは実現できた。

まず、背景色が異なる部分を擬似要素で実装した理由は、余分な(中身が空の)HTMLタグを作らないため。できるだけシンプルにタグを組むことを意識した。

次に、positionプロパティの使い方について、重ねる要素にposition: absolute;を指定、重ねられる要素にposition: relative;を指定した。

疑問・課題

親要素に子要素の画像を重ねる場合、親要素にはposition: relative;を指定、子要素の画像にはposition: absolute;を指定すると学んだ。

しかし、今回の場合、親要素に子要素を重ねるわけではないため、どの要素にどちらの値を指定するのが適切なのか考える必要があった。

うまくいかなかったこと

.textimgを含む親要素.overlapposition: relative;を指定、.overlap::afterposition: absolute;と指定したところ、うまくいかなかった。

実行結果

Image from Gyazo

おわりに

今回は、CSSと擬似要素を使って画像と背景をずらして重ねる方法をまとめた。擬似要素の使い時を考えたり、positionプロパティの使い方を学んだりすることができた。

今後の課題として、上記のうまくいかなかったケースについて、なぜうまくいかなかったのかを説明できるようにしたい。

  1. 画像のレイアウトは、コーディングの手本にしたサイトの一部を大まかに再現したものである。

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