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?

【フロントエンド1000本ノック】0072_picture要素とsource要素を使い、画面サイズに応じて異なる画像(モバイル用、タブレット用、PC用)を出し分ける実装を行え。

Posted at

この記事は人間が書きました

はじめに

こんにちは、赤神です!
この記事は、「1000本ノック」という取り組みの中のフロントエンドのための課題の1つです。

「1000本ノックとは」
https://qiita.com/sora_akagami/items/c8da4296dea3823376ca

※内容としては、前回(0071)の続きです。

width: 100% は、同じ画像を画面に合わせて拡大・縮小するだけでした。

しかし、PC用の巨大な画像をスマホで読み込むのはデータ通信の無駄遣いに繋がります。また、PC用の横長画像をスマホで縮小すると、肝心な部分が見えない場合があり、スマホ用で横長のトリミングした画像を見せたくなります。

これらの問題を解決するのが <piocture> 要素です。これは、 <img> 要素に条件分岐の機能を与えるラッパーのようなものです。

<picture> 要素の仕組み

<picture>要素は、複数の <source> 要素と、1つの <img> 要素で構成されます。

  • <picture>:全体を囲むラッパー。
  • <source>:「もしこの条件(media 属性)に一致したら、この画像(source 属性)を使ってね」という命令。
  • <img>:必須のフォールバック。どの <source> の条件にも一致しなかった場合、または、<picture>. タグを理解できない古いブラウザで表示される画像。

ブラウザは、<source> タグを上から順番にチェックし、最初に一致した条件の画像を読み込みます。つまり、条件が厳しい順に書く必要があります。

作成したコード

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>フロントエンド1000本ノック 0072</title>
</head>
<body>
  <picture>
    <source src="image-large.jpg" media="(min-width: 1024px)">
    <source src="image-medium.jpg" media="(min-width: 600px)">
    <img src="image-small.jpg" alt="画像">
  </picture>
</body>
</html>
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?