2
3

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 5 years have passed since last update.

HTML5で画面サイズごとに画像を差し替える必要がある場合の書き方

Last updated at Posted at 2018-07-24

サイトを作っているときによく「この部分の画像、PC版とスマホ版で最適化したものに差し替えしたいんですよね」という要望をいただくことがあります

HTML5で追加された<picture>要素にはこんなときの解決方法があります
コード例のブレイクポイントは640pxと1024pxにしていますがここは要件に応じて適宜調整してください

caniuse

によれば、IE11以外はだいたい出回ってるブラウザではOKのようです

picture-srcset.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>picture要素とsrcsetの例</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<picture>
    <!-- sourceのmediaにメディアクエリを、srcsetに<img srcset>の記述も対応できるっぽい-->
    <source media="(max-width: 639px)" srcset="http://via.placeholder.com/640x640">
    <source media="(max-width: 1023px)" srcset="http://via.placeholder.com/1024x1024">
    <!-- fallback -->
    <img src="http://via.placeholder.com/1920x1920" alt="image">
</picture>

<!-- IEとかIEとかIEとかで動かないのでpolyfill-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/picturefill/3.0.3/picturefill.min.js"></script>
</body>
</html>
2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?