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?

pictureタグ sourceタグの使い方

Last updated at Posted at 2024-09-11

アジェンダ

<picture>タグと<source>タグを使用して、異なる画面サイズに応じた画像の表示を切り替えることができます。
今回は、画像をSPTabletPCのサイズによって切り替えるというものを例にしながら簡単にまとめます。

HTML例

<section>
  <picture>
    <!-- スマホ用の画像 -->
    <source srcset="path-to-mobile-image.jpg" media="(max-width: 599px)" />
    <!-- タブレット用の画像 -->
    <source srcset="path-to-tablet-image.jpg" media="(min-width: 600px) and (max-width: 1023px)" />
    <!-- PC用の画像 -->
    <source srcset="path-to-desktop-image.jpg" media="(min-width: 1024px)" />
    <!-- PCの画像(対応しないブラウザ用) -->
    <img src="path-to-default-image.jpg" alt="Key Visual" />
  </picture>
</section>

ポイント

  1. <picture>タグを使用して、異なる画像を提供することで、デバイスに合わせた画像の切り替えができます。
  2. <source>タグのmedia属性を使って、画面幅(ブレークポイント)に応じて画像を切り替えます。
    • (max-width: 599px):599px以下の画面(スマホ)
    • (min-width: 600px) and (max-width: 1023px):600px〜1023pxの画面(タブレット)
    • (min-width: 1024px):1024px以上の画面(デスクトップ)
  3. <img>タグはデフォルトの画像を表示するため、対応していないブラウザでも表示されます。

注意: pictureタグ内にimgタグは必ず必要

pictureタグには必ずimgタグを入れる必要があります。

<section>
  <picture>
    <source srcset="path-to-mobile-image.jpg" media="(max-width: 599px)" />
    <source srcset="path-to-tablet-image.jpg" media="(min-width: 600px) and (max-width: 1023px)" />
    <source srcset="path-to-desktop-image.jpg" media="(min-width: 1024px)" />
  </picture>
</section>

参考

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?