1
1

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】レスポンシブ対応で画像を遅延読み込み表示する場合のaspect-ratioの使い方

Last updated at Posted at 2025-03-18

今更ながら…今まで画像比率を保持するために使用していたCSSが
IEサポート終了によって使用できるようになったためメモ:pencil2:

作りたいイメージ

HTML
<div class="content">
  <div class="content-img-wrap">
    <img loading="lazy" src="/app/img/images.jpg" alt="猫img" class="content-img" width="300" height="200">
  </div>
  <p class="content-text">猫ちゃんかわいいね</p>
</div>
今まで

.content-img-wrap {
  position: relative;
  width: 100%;
}

.content-img-wrap::before {
  content: "";
  display: block;
  padding-top: 66.7%; /* 比率を指定(高さ ÷ 横幅 × 100(整数にならない場合は小数点第二位を四捨五入)) */
}

.content-img {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

業務では画像を遅延読み込みする際に発生する画面のカクツキ防止のため、
画像の高さを枠で保持することが多いのでデフォルトではこちらを使用する。

aspect-ratio
.content-img-wrap {
  width: 30%;
  height: auto;
  max-width: 300px; /* 最大表示枠が決まっている場合 */
  aspect-ratio: 3 / 2 /* 明確な比率が決まっていないときは横幅と高さを指定するでもOK */
  overflow: hidden;
  margin-right: 20px;
}

.content-img {
  width: 100%;
  height: auto;
  max-height: 100%;
  object-fit: cover; /* 画像全体を表示させたい場合はcontentとする */
  border-radius: 6px;
}
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?