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?

More than 3 years have passed since last update.

pictureタグでPCとSPで画像を切替える

Last updated at Posted at 2021-06-25

概要

CSSやJavascriptを使用せず、HTMLでレスポンシブに画像切替えを実装した。
IE対応で少し悩んだので備忘録。

使用方法

<picture>
    <source srcset="{画像1のパス}" media="({画面サイズ})" />
    <img src="{画像2のパス}" />
</picture>
  • pictureタグの中にsorurceとimgタグを書く
  • 画像の切替えは、media="({画面サイズ})"で画像サイズを指定して行う。
  • 一番上に記載したsourceから順に、条件に当てはまったsourceタグの画像が適用される。
  • どのsourceの条件にも当てはまらない場合は、imgタグの画像が適用される。

使用例

使用例)
<picture>
    <source srcset="./img/img0.png" media="(min-width: 835px)"/> ---優先度1---
    <source srcset="./img/img1.png" media="(max-width: 1200px)"/> ---優先度2---
    <img src="./img/img2.png" /> ---↑の条件に当てはまらない場合---
</picture>
  • mediaで画面サイズが835pxより大きいの場合の画像を指定
  • mediaで画像サイズが1200pxより小さい場合の画像を指定

IE対応メモ

↓の使用例でsourceタグはPC用の画像・imgタグはSP用の画像パスを指定すると仮定。

使用例)
<picture>
    <source srcset="./img/img_pc.png" media="(min-width: 835px)"/> <= PC用の画像指定
    <img src="./img/img_sp.png" width="100" height="100"/> <= SP用の画像指定
</picture>
  • imgタグで画像のwidthheightを指定

    => 指定しないとSPサイズで画像が切り替わらないため、必ず画像の高さと幅を指定する。

  • widthheightはPC用の画像サイズを指定

    => imgはSP用の画像だから...と思ってSPの画像サイズを指定すると、sourceで指定したPC用の画像もSPの画像と同じサイズになってしまう。

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?