title: When Responsive Images Get Ugly
url: http://codepen.io/Tigt/post/when-responsive-images-get-ugly
hash_url: 16d800a1faadde1445d0c2332f5b6f3c

<p>I don’t know about you, but I’m over the current crop of “How to use our new friends <code>&lt;picture&gt;</code> and <code>srcset</code>” tutorials. They show you some Baby’s First Markup which is nice for teaching purposes, but doesn’t prepare you for the ugliness that more… unusual applications require.</p>

<p>I’ve encountered a few corner-cases and quirks to beware of and found a few of said unusual applications. Maybe they can help you.</p>

<nav class="toc">
  <h2>Contents</h2>
  <ol>
    <li><a href="#some-ground-floor-stuff">Some ground floor stuff</a>
      <ol>
        <li><a href="#why-bother">Why bother?</a></li>
        <li><a href="#srcset-is-preferable">srcset is preferable</a></li>
      </ol>
    </li>
    <li><a href="#unintuitive-behavior-gotchas">Unintuitive behavior &amp; gotchas</a>
      <ol>
        <li><a href="#media-conditions-not-media-queries">Media conditions, NOT media queries</a></li>
        <li><a href="#troublesome-css-units">Troublesome CSS units</a></li>
        <li><a href="#sizes-will-affect-how-your-image-displays">sizes will affect how your image displays</a></li>
      </ol>
    </li>
    <li><a href="#media-aware-images">Media-aware images</a>
      <ol>
        <li><a href="#printer-friendly">Printer-friendly</a></li>
        <li><a href="#e-ink-friendly">E-ink-friendly</a></li>
        <li><a href="#night-mode-bright-sunlight">Night mode &amp; bright sunlight</a></li>
      </ol>
    </li>
    <li><a href="#the-deepest-backwards-compatibility-possible">The deepest backwards-compatibility possible</a></li>
    <li><a href="#height-and-width-constrained-srcset">Height and width-constrained srcset</a>
      <ol>
        <li><a href="#object-fit-cover">object-fit: cover</a></li>
        <li><a href="#object-fit-contain">object-fit: contain</a></li>
      </ol>
    </li>
    <li><a href="#responsive-bitmaps-inside-inline-svg">Responsive bitmaps inside inline SVG</a>
      <ol>
        <li><a href="#fixing-ie">Fixing IE</a></li>
        <li><a href="#building-the-sizes">Building the sizes</a></li>
        <li><a href="#making-things-worst-with-not-quite-entire-viewport-scaling">Making things worst with not-quite-entire-viewport scaling</a>
          <ol>
            <li><a href="#the-browser-viewport">The browser viewport</a></li>
            <li><a href="#the-svg-element">The <code>&lt;svg&gt;</code> element</a></li>
            <li><a href="#the-viewbox">The viewBox</a></li>
            <li><a href="#the-image">The <code>&lt;image&gt;</code></a></li>
            <li><a href="#assembling">Assembling</a></li>
          </ol>
        </li>
      </ol>
    </li>
    <li><a href="#thats-all-folks">That’s all, folks</a></li>
  </ol>
</nav>

<h2 id="some-ground-floor-stuff">Some ground floor stuff</h2>

<p>I’m assuming you already have a basic grasp of responsive images. If not, I recommend <a href="http://blog.cloudfour.com/responsive-images-101-definitions/">Cloud Four’s introduction series</a>.</p>

<h3 id="why-bother">Why bother?</h3>

<p>If the ensuing code has you despairing that responsive images are more trouble than they’re worth, refer to this section to remember that <strong>overlarge images are painful,</strong> in a variety of ways:</p>

<dl class="bulleted">
  <dt>Download size</dt>
  <dd>Doubling an image’s pixel density quadruples its area and can <em>sextuple</em> its filesize! Have a data plan? Not anymore you don’t.</dd>
  <dt>CPU load &amp; battery drain</dt>
  <dd>Images also need to be decoded. Shrinking ‘em with CSS? Now the browser needs to scale and resample, too. The difficulty of all three grows exponentially with image size.</dd>
  <dt>Memory usage</dt>
  <dd>Big photographs <a href="https://twitter.com/keithclarkcouk/status/605983582709010432">can cause juddering in a mobile browser all by themselves</a>. Resizing with CSS doesn’t help; the browser keeps the full thing around for zooming.</dd>
</dl>

<p>An oversized image wastes time, bandwidth, data, battery, and system resources. Even if you don’t use a polyfill, you should use responsive images for <a href="http://caniuse.com/#feat=srcset">the 56% (and growing!) of browsers that support them</a>; anything else would be irresponsible.</p>

<h3 id="srcset-is-preferable"><code>srcset</code> is preferable</h3>

<p><code>&lt;picture&gt;</code> is darling, but a plain <code>&lt;img srcset&gt;</code> is more flexible: bandwidth-saving modes, browser heuristics, and user choices. It’s also more future-friendly; <code>&lt;picture&gt;</code> is only as good as your media queries. <code>srcset</code> is the smart choice.</p>

<h2 id="unintuitive-behavior-gotchas">Unintuitive behavior &amp; gotchas</h2>

<p>Like everything else on the front-end, responsive images are fraught with edge cases and unforeseen applications. I’ve collected a couple things that have tripped me up, in the hopes that they won’t do the same to you.</p>



<p>The most important <em>and</em> trickiest part of responsive images is the <code>sizes</code> attribute. If it doesn’t tell the browser <em>exactly</em> how big the image is going to be, you risk either a scaled-up mess or a scaled-down bloat. So naturally the <code>sizes</code> syntax is error-prone.</p>

<p>In Standardese, the <code>sizes</code> attribute takes a comma-separated list of <code>&lt;source-size-value&gt;</code>s, which break down into a <b>media condition</b> (not a media query!) and a <b>length</b>, like this:</p>

<pre>
  <code>sizes="(media: condition) length,
       (media: condition) length,
       (media: condition) length"
</code>
</pre>

<p>The length is the width of the image if the media condition is true. It accepts a value, like <code>700px</code>, or a <code>calc()</code> expression.</p>

<p>Media conditions are almost media queries. The spec <a href="http://www.w3.org/TR/mediaqueries-4/#typedef-media-condition">codifies them in a formal CSS grammar</a>, but for us <em>mere mortals</em> the rules are:</p>

<ul>
  <li>You cannot use media types (<code>screen</code>, <code>print</code>, <code>tv</code>, etc.)</li>
  <li>Use any <code>(feature: value)</code> pairs you like.</li>
  <li>You can chain them with the keywords <code>and</code>, <code>or</code>, and <code>not</code>. Do <strong>not</strong> use commas as a substitute for <code>or</code>.</li>
  <li>If using the <code>or</code> or <code>not</code> keywords, you must wrap the entire media condition in parentheses.</li>
  <li>If empty, it always evaluates to true.</li>
</ul>

<p>But I've always preferred examples. Much simpler to get the shape of things from them than trying to string together a buncha rules.</p>

<figure>
  <figcaption>Some valid media conditions:</figcaption>

  <ul>
    <li><code>(min-width: 500px)</code>
    </li><li><code>(max-width: 300px) and (orientation: portrait)</code>
    </li><li><code>((min-height: calc(50vw - 100px)) or (light-level: dim))</code>
    </li><li><code> </code> (Yep, an empty M.C. is totes O.K.)
    </li>
  </ul>
</figure>

<figure>
  <figcaption>Some valid lengths:</figcaption>

  <ul>
    <li><code>200px</code>
    </li><li><code>40em</code>
    </li><li><code>calc(40rem - 10vw)</code>
    </li><li><code>78.95vmax</code>
    </li>
  </ul>
</figure>

<figure>
  <figcaption>Some valid <code>&lt;source-size-value&gt;</code>s:</figcaption>

  <ul>
    <li><code>(min-width: 500px) 200px</code>
    </li><li><code>(max-width: 300px) and (orientation: portrait) 40em</code>
    </li><li><code>((min-height: calc(50vw - 100px)) or (light-level: dim)) calc(40rem - 10vw)</code>
    </li><li><code>78.95vmax</code>
    </li>
  </ul>
</figure>

<p>Ugly? Sure. Powerful? You bet.</p>

<p>Now, because this is web development, and <em>nothing can ever be easy</em>, browsers aren’t required to have fully implemented media condition grammar before they implement responsive images. You may need backup conditions to work around that:</p>

<pre>
  <code>"((min-height: calc(50vw - 100px)) or (light-level: dim)) 500px,
 (min-height: calc(50vw - 100px) 500px,
 (light-level: dim) 500px"
</code>
</pre>

<p>As always, test, test, test. I recommend <a href="http://placehold.it/">placehold.it</a> for images that explicitly indicate their widths; lessens ambiguity and saves you from having to check the <code>currentSrc</code> every time.</p>

<h3 id="troublesome-css-units">Troublesome CSS units</h3>

<p>
  <a href="http://www.w3.org/TR/html51/semantics.html#source-size-value">So sayeth the spec:</a>
</p>

<blockquote>
  <p><b>Note:</b> Percentages are not allowed in a <code>&lt;source-size-value&gt;</code>, to avoid confusion about what it would be relative to. The vw unit can be used for sizes relative to the viewport width.</p>
</blockquote>

<p>The browser image preloader wants the proper URL to request ASAP. It’s not waiting around for your CSS to download and parse, it needs units it can use <em>now.</em> And since the <code>%</code> unit only works if you know how big an element’s parents are, the CSS is required to calculate it.</p>

<p><code>rem</code> and <code>em</code> <em>are</em> supported, but be careful. They’re resolved <a href="http://ircbot.responsiveimages.org/bot/log/respimg/2015-06-04#T132199">like they are inside media queries</a>: equal to the user’s default <code>font-size</code>. (Which is often 16px, but not always.) If you’re respecting that default, you should be good to go.</p>

<p>But if you’re doing something like <code>html {font-size: 10px}</code> to make the math easier, well, don’t. That <a href="https://vasilis.nl/nerd/using-pixels-polite/">doesn’t respect the user</a>, and it prevents you from using <a href="http://blog.cloudfour.com/the-ems-have-it-proportional-media-queries-ftw/">the power of <code>em</code>s in media queries</a>.</p>

<p>You also can’t do <code>html {font-size: 62.5%}</code> if you want to use <code>em</code> in <code>sizes</code>. What with preprocessors nowadays you don’t need to, and <a href="http://www.filamentgroup.com/lab/how-we-learned-to-leave-body-font-size-alone.html">embracing the default user <code>font-size</code> is a good practice</a>. Prevents a lot of <a href="https://vasilis.nl/nerd/weird-62-5-antipattern/">inheritance woes</a>.</p>

<p>As for why you’d size an image with <code>em</code>in the first place…</p>

<ul>
  <li>If your breakpoints are using <code>em</code>, you'll reflect them in your media conditions.</li>
  <li>If you’re sizing your text container with <code>em</code>s for <a href="http://maxdesign.com.au/articles/ideal-line-length-in-ems/">the perfect line length</a>, and images inside it are <code>max-width: 100%</code>, they can end up sized in <code>em</code>s too.</li>
</ul>

<p>As for those weirdo units, like <code>ch</code> or <code>ex</code> or <code>pc</code>… If you use them, Tim Berners-Lee calls Håkon W. Lie, who calls Bert Bos, and <em>he</em> calls the authorities.</p>

<h3 id="sizes-will-affect-how-your-image-displays"><code>sizes</code> <em>will</em> affect how your image displays</h3>

<p><code>sizes</code> appears to be just hints about how your CSS scales the image, but it actually changes how the image will be displayed all on its own. Observe:</p>

<p/><p data-slug-hash="XbRaVP" data-default-tab="result" data-height="900" data-theme-id="14446" class="codepen"/>

<p>If your screen is big, you can see the last image is way enormous. It doesn't have a <code>sizes</code> attribute, and browsers assume <code>sizes="100vw"</code> when that happens. Widespread misuse of this default is why <a href="http://alistapart.com/blog/post/article-update-dont-rely-on-default-sizes">it’s no longer valid to omit <code>sizes</code> on a responsive image</a>.</p>

<p>If you aren’t using CSS to explicitly size the image at all times, like if you’ve got <code>img { max-width: 100% }</code> and not all your images will be as big as their containers, be careful and test to make sure your <code>sizes</code> attribute isn’t running amok. Browsers treat the length of the chosen <code>&lt;source-size-value&gt;</code> like <code>&lt;img width&gt;</code>: if you don’t override it with CSS, that’s how wide it will be.</p>



<p>Using <code>&lt;picture&gt;</code> and the full power of the <code>media</code> attribute, you can make especially important images (logos, diagrams, etc.) adapt best to device capabilities and circumstances.</p>

<h3 id="printer-friendly">Printer-friendly</h3>

<pre>
  <code class="html">&lt;picture&gt;
  &lt;source srcset="logo-printer-friendly.svg" type="image/svg+xml" media="print, (monochrome: 1)"&gt;

  &lt;img src="logo.png" alt="Butt-Touchers Incorporated"&gt;
&lt;/picture&gt;
</code>
</pre>

<p>You’ve probably seen print stylesheet tutorials that <code>display: none</code> images and substitute printer-friendly versions as background images. Since not all browsers print with background images &amp; colors on (at least, not by default), this version is much more robust. For important content images, it’s <em>way</em> better.</p>

<p>I also specify the image for devices that can’t display colors (<code>monochrome: 1</code>), because hey, we already made a B&amp;W version for saving ink.</p>

<h3 id="e-ink-friendly">E-ink-friendly</h3>

<p>A device that qualifies for <code>update-frequency: slow</code> (mostly e-Ink devices) probably wouldn’t play GIFs, but if it did, it would look very muddy and blurry as it would struggle to keep up.</p>

<p>In either case, it would be much nicer to display a still frame that’s representative of the GIF instead. (As opposed to showing the first frame, which is an often unsuitable default.) So that’s what we do here, and hey, print doesn't have an update frequency, right?:</p>

<pre>
  <code class="html">&lt;picture&gt;
  &lt;source srcset="reaction-frame.png" media="print, (update-frequency: slow)"&gt;

  &lt;img src="reaction.gif" alt="Say whaaaaat?"&gt;
&lt;/picture&gt;
</code>
</pre>

<h3 id="night-mode-bright-sunlight">Night mode &amp; bright sunlight</h3>

<pre>
  <code class="html">&lt;picture&gt;
  &lt;source srcset="floorplan-dark.svg" media="(light-level: dim)"&gt;
  &lt;source srcset="floorplan-hicontrast.svg" media="(light-level: washed)"&gt;

  &lt;img src="floorplan.png" alt="The plans for how we'll renovate the apartment." longdesc="#our-plans" aria-describedby="our-plans"&gt;
&lt;/picture&gt;
</code>
</pre>

<p>Using light level media queries, we can adapt images to be higher contrast and visible in strong sunlight conditions (<code>washed</code>), or invert the colors to be less distracting in the dark (<code>dim</code>).</p>

<p>These aren’t features you should scramble to implement, but keep them in your back pocket. The print-friendly one is useful today, <code>light-level</code> is gaining implementation (Firefox already supports it), and cheapo e-Ink displays have a wealth of possibilities for hardware innovation we haven’t seen yet.</p>

<p>And you never know; you might someday find an obscure media query is perfect for your project, like <code>color-index</code> or <code>scan</code>.</p>

<h2 id="the-deepest-backwards-compatibility-possible">The deepest backwards-compatibility possible</h2>

<p>Start with a boring ol’ HTML 2.0 <code>&lt;img&gt;</code>:</p>

<pre>
  <code class="html">&lt;img src="giraffe.jpg" alt="A giraffe."
     height="400" width="300"&gt;
</code>
</pre>

<p>The key realization is that once we add <code>sizes</code> to this <code>&lt;img&gt;</code>, browsers that understand <code>&lt;picture&gt;</code> and width-based <code>srcset</code> will <em>ignore</em> the <code>src</code>, <code>height</code>, and <code>width</code> attributes.</p>

<p><i>“Width-based <code>srcset</code>? What?”</i> Ah, my fine hypothetical friend, there are two kinds of <code>srcset</code> lists:</p>

<dl>
  <dt>Width-based</dt>
  <dd><code>srcset="giraffe@1x.jpg 300w, giraffe@1.5x.jpg 450w, giraffe@2x.jpg 600w, giraffe@3x.jpg 900w"</code></dd>
  <dt>Pixel density-based</dt>
  <dd><code>srcset="giraffe@1.5x.jpg 1.5x, giraffe@2x.jpg 2x, giraffe@3x.jpg 3x"</code></dd>
</dl>

<p>The pixel density-based <code>srcset</code> (with the <code>x</code> descriptor) is the only kind that <a href="http://caniuse.com/#search=srcset">works in Safari, some earlier versions of Chrome &amp; Opera, and Microsoft Edge right now</a>. The newer width-based version (with the <code>w</code> descriptor) <a href="http://caniuse.com/#feat=picture">only works in the newest versions of Firefox, Opera, and Chrome</a>.</p>

<p>We want to make our images as responsive as can be, so we should use both kinds of <code>srcset</code>, if possible. And we can! Just not quite how you would think. If we were to use a <code>srcset</code> with both <code>x</code> and <code>w</code> descriptors in it, like this:</p>

<pre>
  <code>srcset="giraffe.jpg 100w, giraffe@2x.jpg 2x"
</code>
</pre>

<p>Well, browsers will do <em>something,</em> but I guarantee it won’t be what you want. We’ll have to get multiple <code>srcset</code>s involved, using <code>&lt;picture&gt;</code> and <code>&lt;source&gt;</code>.</p>

<p>First, for the almost-modern browsers, I'll bolt on the <code>x</code> descriptor <code>srcset</code>:</p>

<pre>
  <code class="html">&lt;img src="giraffe.jpg" alt="A giraffe."
 srcset="giraffe@1.5x.jpg 1.5x,
         giraffe@2x.jpg 2x,
         giraffe@3x.jpg 3x"
 height="400" width="300"&gt;
</code>
</pre>

<p>Unlike the <code>w</code> descriptor <code>srcset</code>, the <code>x</code> kind <em>does</em> take the <code>src</code> attribute into account. It assumes it’s <code>1x</code>, so you don’t have to specify it again. </p>

<p>For <code>x</code> <code>srcset</code>, the <code>width</code> and <code>height</code> attributes just keep on doin’ what they’re doin’; all it does is swap out the image’s source if it’s on a higher-density screen. The new high-resolution source will take up the same amount of “CSS pixels” as before.</p>

<p>Next, we’ll turbocharge the markup for browsers that understand <code>w</code> descriptor <code>srcset</code>:</p>

<pre>
  <code class="html">&lt;picture&gt;
    &lt;source srcset="giraffe@1x.jpg 300w,
                    giraffe@1.5x.jpg 450w,
                    giraffe@2x.jpg 600w,
                    giraffe@3x.jpg 900w"
            sizes="300px" type="image/jpeg"&gt;

    &lt;img src="giraffe.jpg" alt="A giraffe."
         srcset="giraffe@1.5x.jpg 1.5x,
                 giraffe@2x.jpg 2x,
                 giraffe@3x.jpg 3x"
         height="400" width="300"&gt;
&lt;/picture&gt;
</code>
</pre>

<p><i>“Hey, I thought you said that we should prefer plain <code>srcset</code>!”</i>  Indeed, I did. If you look at the lone <code>&lt;source&gt;</code> element, we don’t have a <code>media</code> attribute, so browsers will use its <code>srcset</code> just like if it were on the <code>&lt;img&gt;</code> element instead. Same effect! (Note: the <code>type="image/jpeg"</code> isn't <em>necessary,</em> but the HTML won't validate without it.)</p>

<p>This setup is as good as it gets, unless you want a responsive image polyfill for browsers that don’t understand <em>any</em> form of <code>srcset</code>. Me, I’m fine serving a sensible fallback <code>src</code> for my sites. Just don’t make it enormous!</p>

<h2 id="height-and-width-constrained-srcset">Height <strong>and</strong> width-constrained <code>srcset</code></h2>

<p>Say you’ve got a nice big, fullscreen image. It’s a content image, not style, so you’re using an actual <code>&lt;img&gt;</code> instead of a <code>background-image</code>. You want to responsify it, because fullscreen on a phone is orders of magnitude different from fullscreen on desktop.</p>

<p>The first question is, is your image acting like <code>contain</code> or <code>cover</code>?</p>

<p>If you know how CSS’s <code>background-size</code> or <code>object-fit</code> properties work, that’s what I’m asking. Is your image going to get as big as it can without cropping itself, or is it covering up an element entirely and not leave any empty space? If you’re confused, <a href="http://davidwalsh.name/demo/background-size.html">try playing with David Walsh’s demo</a>.</p>

<h3 id="object-fit-cover">
  <code>object-fit: cover</code>
</h3>

<p>This one is easy: just set <code>sizes</code> to <code>100vw</code>.</p>

<pre>
  <code class="html">&lt;img srcset="..." sizes="100vw" alt="A giraffe."&gt;
</code>
</pre>

<h3 id="object-fit-contain">
  <code>object-fit: contain</code>
</h3>

<p>This one is hard.</p>

<p>The problem is, <code>srcset</code> currently only does widths. <a href="https://github.com/ResponsiveImagesCG/picture-element/issues/86">There is an <code>h</code> descriptor coming</a>, but it doesn’t do us any good now. Are we doomed to make our images too tall, or to use <code>&lt;picture&gt;</code> and micromanage the browser logic?</p>

<p>I shouted my despair into the ether, that is, <a href="http://stackoverflow.com/questions/29778235/can-i-use-picture-for-both-height-and-width-constrained-images">asked StackOverflow for ideas</a>. The inestimable <a href="https://github.com/aFarkas">Alexander Farkas</a>, maintainer of <a href="https://github.com/aFarkas/html5shiv">the HTML5shiv</a> since 2011, and the author of/contributor to loads of awesome <a href="https://github.com/scottjehl/picturefill">responsive</a> <a href="https://github.com/aFarkas/respimage">image</a> <a href="https://github.com/aFarkas/lazysizes">solutions</a>, swooped in and <a href="http://stackoverflow.com/a/29781000">nailed it in one</a>:</p>

<blockquote>
  <p>I think I got it (1/2) is equal to (width/height):</p>

  <pre><code>&lt;img
   srcset="http://lorempixel.com/960/1920/sports/10/w1920/ 960w"
   sizes="(min-aspect-ratio: 1/2) calc(100vh * (1 / 2))"
  /&gt;</code></pre>
</blockquote>

<p>Pretty brilliant. I’ll explain this terse code example, because I sure as heck had to go over it several times myself.</p>

<p>The lynchpin of the entire operation is the image’s <strong>aspect ratio.</strong> Without that, we can’t do a blamed thing.</p>

<p>Thankfully, it’s straightforward: divide the image’s width by its height. This gets you the “aspect multiplier” (probably not a real term). The actual aspect <em>ratio</em> is that multiplier written as a simplified fraction. It’s commonly separated like 16:9, but in CSS it’s <code>16/9</code>.</p>

<p>So if you had an image 300 pixels by 500 pixels, and another 600 pixels by 1000 pixels, they’d both have an aspect ratio of 3:5, or <code>3/5</code> in CSS.</p>

<p>Let's pretend we have an image with aspect ratio 4:5. In English, our logic is:</p>

<ol>
  <li>If the screen’s aspect ratio is wider (greater) than the image’s aspect ratio, the image will be the full height of the screen.</li>
  <li>Otherwise, the image will be the full width of the screen.</li>
</ol>

<p>Using our <code>4/5</code> aspect ratio image from earlier, that translates to:</p>

<pre>
  <code class="html">&lt;img sizes="(min-aspect-ratio: 4/5) 80vh, 100vw"&gt;
</code>
</pre>

<p>Whoah! Where did that <code>80vh</code> come from?</p>

<p>This is the part I had trouble with. The first thing to understand is that we’re still telling the browser how <em>wide</em> the image is going to be. <strong>We</strong> know it’s going to be <code>100vh</code> tall, but we need to inform the browser what width that entails. Since we have the aspect ratio, and we have the height, we just need to solve for the width.</p>

<dl class="proof">
  <dt class="math">Ratio = width ÷ height</dt>
  <dd>An image’s aspect ratio is its width divided by its height</dd>
  <dt class="math">⅘ = width ÷ 100vh</dt>
  <dd>Fill in our known values</dd>
  <dt class="math">width = ⅘ × 100vh</dt>
  <dd>Isolate the <var>width</var> variable</dd>
  <dt class="math">width = 80vh</dt>
  <dd>Simplify.</dd>
</dl>

<p>
  <small>(I wish more than just Firefox &amp; Safari implemented MathML.)</small>
</p>

<p>The second <code>sizes</code> argument, the lone <code>100vw</code> length, is for when the viewport is tall enough that the image is width-constrained, which means it will take up the entire screen width. It’s actually optional, since browsers will assume <code>100vw</code> by default if no media conditions are true. So we can slim down to <code>sizes="(min-aspect-ratio: 4/5) 80vh"</code>.</p>

<p>That’s the hard part over with. <code>srcset</code> is just a list of images and widths, after all. Since this image should fill the screen of everyone, no matter the size, we’ll run the gamut between itty-bitty 300 pixels and big honking 4000 pixels. (Though what with smartwatches and those new 5k screens, that may not be enough…)</p>

<pre>
  <code class="html">&lt;img sizes="(min-aspect-ratio: 4/5) 80vh"
     src="giraffe.png"
     srcset="giraffe@0.75x.jpg 300w,
             giraffe.png       400w,
             giraffe@1.5x.jpg  600w,
             giraffe@2x.jpg    800w,
             giraffe@2.5x.jpg  1000w,
             giraffe@3x.jpg    1200w,
             giraffe@3.5x.jpg  1400w,
             giraffe@4x.jpg   1600w,
             [...pretend I wrote out everything in between]
             giraffe@9.5x.jpg  3800w,
             giraffe@10x.jpg   4000w"
     alt="A giraffe."&gt;
</code>
</pre>

<p>Is that an excessive amount of <code>srcset</code> choices? Yeah, probably. There’s no silver bullet to figure out what widths to include, so you’ll have to experiment with what works for your site. It <strong>is</strong> a lot of markup, but the HTML weight gain is more than paid back with properly-sized images.</p>

<h2 id="responsive-bitmaps-inside-inline-svg">Responsive bitmaps inside inline SVG</h2>

<p>My personal use-case is shoving raster images inside <code>&lt;svg&gt;</code>. You are probably not doing that, but the remainder of this blog post is as good an example as it gets for “how ugly can responsive images really be?”</p>

<p>Answer: <strong>THIS UGLY.</strong> Children and the squeamish are allowed to cover their faces during the upsetting parts.</p>

<p>Anyway, say I embed the raster image like this:</p>

<pre>
  <code class="html">&lt;image xlink:href="giraffe.png" x="5" y="13" width="200" height="400"&gt;
    &lt;title&gt;A giraffe.&lt;/title&gt;
&lt;/image&gt;
</code>
</pre>

<p>This has two problems:</p>

<ol>
  <li>SVG doesn’t have anything like <code>srcset</code>. You get the one <code>xlink:href</code>, <strong>and you’ll like it.</strong></li>
  <li>Browser preloaders don’t fetch it like they do with your usual <code>&lt;img src&gt;</code>. This is not a trivial slowdown; other assets (scripts, background images, etc.) can get scheduled before it, blocking the image.</li>
</ol>

<p>We can solve both issues in one fell swoop with <code>&lt;foreignObject&gt;</code>:</p>

<pre>
  <code class="html">&lt;foreignObject x="5" y="13" width="200" height="400"&gt;
    &lt;img src="giraffe.png" srcset="image@2x.png 2x, etc..." alt="A giraffe."&gt;
&lt;/foreignObject&gt;
</code>
</pre>

<p>It can get as fancy as we want in there; <code>&lt;foreignObject&gt;</code> accepts any HTML that can go inside <code>&lt;body&gt;</code>. <strong><em>Except in Internet Explorer.</em></strong> (Edge, thankfully, does support <code>&lt;foreignObject&gt;</code>.)</p>

<h3 id="fixing-ie">Fixing IE</h3>

<p>IE9, 10, &amp; 11 all don’t support <code>&lt;foreignObject&gt;</code>, but hope is not lost: just use <code>&lt;switch&gt;</code> to give them <code>&lt;image</code> instead:</p>

<pre>
  <code class="html">&lt;switch&gt;
    &lt;foreignObject x="5" y="13" width="200" height="400"
                             requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"&gt;
        &lt;img src="giraffe.png" srcset="image@2x.png 400w, etc..." alt="a giraffe"&gt;
    &lt;/foreignObject&gt;

    &lt;image xlink:href="giraffe.png" x="5" y="13" width="200" height="400"&gt;
        &lt;title&gt;a giraffe&lt;/title&gt;
    &lt;/image&gt;
&lt;/switch&gt;
</code>
</pre>

<p>That <code>requiredFeatures</code> attribute lets IE know that the <code>&lt;foreignObject&gt;</code> element requires the features described at that URL. IE doesn’t like, look it up or anything, the URLs of what a browser supports are hardcoded in.</p>

<p>A neat side-effect is that IE’s preloader will grab what’s inside the <code>src</code> it won’t use, but it’s the same URL as the <code>xlink:href</code> it <em>will</em> use. Bonus!</p>

<h3 id="building-the-sizes">Building the <code>sizes</code></h3>

<p>I’ve got a remaining wrinkle to deal with. The images don’t take up all of their <code>&lt;svg&gt;</code> parent’s space, and they each have their own aspect ratios! </p>

<p>The first step to making sense of the mess is finding out what percentage of the <code>&lt;svg&gt;</code>’s dimensions each of the images’ dimensions take up. For a setup like this:</p>

<pre>
  <code class="html">&lt;svg viewBox="0 0 1400 1600" preserveAspectRatio="xMidYMid"&gt;
    &lt;image x="200" y="200" width="1000" height="1200"/&gt;
&lt;/svg&gt;
</code>
</pre>

<p>(On the <code>&lt;svg&gt;</code> element, I’ve placed <code>preserveAspectRatio="xMidYMid"</code>, which has the viewBox act like <code>object-fit: contain</code> and center itself. )</p>

<p>The image is roughly 71.43% the width of the <code>&lt;svg&gt;</code> (1000 ÷ 1400), and 75% the height (1200 ÷ 1600). We could write a basic program to do that math for us. But assembling that information into a usable <code>sizes</code> eluded me. Here were my conditions:</p>

<ol class="proof">
  <li>If the screen’s aspect ratio is wider (greater) than the <code>&lt;svg&gt;</code>’s aspect ratio (7:8), the <code>&lt;svg&gt;</code> is height-constrained. Otherwise, it’s width-constrained.</li>
  <li><p>When the <code>&lt;svg&gt;</code> is width-constrained:</p>
    <dl>
      <dt class="math">Image’s display width = 100vw × 71.43%</dt>
      <dt class="math">Image’s display width = 71.43vw</dt>
      <dd>The <code>&lt;svg&gt;</code> will be 100vw wide, and the image will be 71.43% the width of that.</dd>
    </dl>
  </li><li><p>When the <code>&lt;svg&gt;</code> is height-constrained:</p>
  <dl>
    <dt class="math">Image’s display height = 100vh × 75%</dt>
    <dt class="math">Image’s display height = 75vh</dt>
    <dd>The <code>&lt;svg&gt;</code> will be 100vh tall, and the image will be 75% the height of that. However, we need its <em>width</em> for <code>sizes</code>.</dd>
    <dt class="math">Ratio = width ÷ height</dt>
    <dd>We’ll use the definition of aspect ratio again…</dd>
    <dt class="math">⅚ = width ÷ 75vh</dt>
    <dd>Substitute the values we know…</dd>
    <dt class="math">62.5vh = width</dt>
    <dd>And solve.</dd>
  </dl>
  </li>
</ol>

<p>Phew. After crunching the numbers, our <code>sizes</code> will look like this:</p>

<pre>
  <code>sizes="(min-aspect-ratio: 7/8) 71.43vw, 62.5vh"
</code>
</pre>

<p>Which, despite the contortions I took to make it, isn’t too scary-looking. Putting everything together, we end up with:</p>

<pre>
  <code class="html">&lt;svg viewBox="0 0 1400 1600" preserveAspectRatio="xMidYMid"&gt;
    &lt;switch&gt;
        &lt;foreignObject x="200" y="200" width="1000" height="1000" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"&gt;
            &lt;img src="giraffe.png" srcset="image@2x.png 400w, etc..." alt="A giraffe." sizes="(min-aspect-ratio: 7/8) 71.43vw, 62.5vh"&gt;
        &lt;/foreignObject&gt;

        &lt;image xlink:href="giraffe.png" x="200" y="200" width="1000" height="1200"&gt;
            &lt;title&gt;A giraffe.&lt;/title&gt;
        &lt;/image&gt;
    &lt;/switch&gt;
&lt;/svg&gt;
</code>
</pre>

<p>Complicated, yes. But so is the Web.</p>

<h3 id="making-things-worst-with-not-quite-entire-viewport-scaling">Making things worst with not-quite-entire-viewport scaling</h3>

<p>As a final problem, I’m going to have interface chrome for navigating these SVGs, so I won’t have the full viewport available. I’ll need a fancier <code>sizes</code>.</p>

<p>First, I need to know how much space the chrome will use. It’s set up to behave like this:</p>

<ol>
  <li>If the screen is wider than it is tall (<code>orientation: landscape</code>), there’s chrome on all four sides. The horizontal chrome takes up 200 pixels, and the vertical chrome takes up 100 pixels.</li>
  <li>Otherwise, the chrome only takes up vertical space. It will be 200 pixels tall.</li>
</ol>

<p>So now I’ve got <strong>four</strong> boxes to analyze:</p>

<ol>
  <li>The browser viewport</li>
  <li>The available space within that viewport once the chrome is done, taken up by the <code>&lt;svg&gt;</code> element</li>
  <li>The SVG viewport (“viewBox”)</li>
  <li>The <code>&lt;image&gt;</code> as constrained by the viewBox.</li>
</ol>

<p>(If any parts of this process have horrible browser bugs, <em>I’m going to be the first to find out.</em>)</p>

<h4 id="the-browser-viewport">The browser viewport</h4>

<p>Simple enough:</p>

<ul>
  <li>width = 100vw</li>
  <li>height = 100vh</li>
  <li>aspect-ratio = 100vw/100vh</li>
</ul>

<h4 id="the-ltsvg-element">The <code>&lt;svg&gt;</code> element</h4>

<ol class="proof">
  <li>
    <p>If the viewport is wider than it is tall (<code>orientation: landscape</code>):</p>
    <dl>
      <dt class="math">width = <code>calc(100vw - 200px)</code></dt>
      <dd>The chrome will take up 200px of width, so the width available is the full width (100vw) minus that (200px).</dd>
      <dt class="math">height = <code>calc(100vh - 100px)</code></dt>
      <dd>The chrome will take up 100px of height, and we calculate what’s left like we did with the width.</dd>
      <dt class="math">aspect ratio = <code>calc((100vw - 200px) / (100vh - 100px))</code></dt>
      <dd>Substitute the values into the equation for calculating aspect ratios.</dd>
    </dl>
    <p><small>(I’m using <code>calc()</code> because the units don’t match, and only the browser will know how to calculate them together.)</small></p>
  </li>
  <li>
    <p>Otherwise:</p>
    <dl>
      <dt class="math">width = 100vw</dt>
      <dd>There’s no horizontal chrome at all when the browser is <code>orientation: portrait</code>, so it’s just 100vw.</dd>
      <dt class="math">height = <code>calc(100vh - 200px)</code></dt>
      <dd>There is 200px of vertical chrome, though.</dd>
      <dt class="math">aspect ratio = <code>calc(100vw / (100vh - 200px))</code></dt>
      <dd>And substitute again.</dd>
    </dl>
  </li>
</ol>

<h4 id="the-viewbox">The viewBox</h4>

<p>We’ll use the <code>&lt;svg&gt;</code> from last time:</p>

<pre>
  <code class="html">&lt;svg viewBox="0 0 1400 1600" preserveAspectRatio="xMidYMid"&gt;
    ...
&lt;/svg&gt;
</code>
</pre>

<p>Unlike the browser viewport and the <code>&lt;svg&gt;</code> element, the aspect ratio of the viewBox doesn’t change when the orientation does. It’s also defined right inside the <code>viewBox</code> attribute. We could technically use <code>1400/1600</code>, but I’ll simplify it to <code>7/8</code>.</p>

<p>As for the height and width, we have two media conditions that we need to check:</p>

<ol>
  <li>Is the browser viewport wide or tall?`</li>
  <li>Does the available space have a wider or narrower aspect ratio than the viewBox?</li>
</ol>

<p>The first one is still <code>(orientation: landscape)</code>, but the chrome has complicated the second. Ideally, I could do <em>this</em>:</p>

<pre>
  <code>(min-aspect-ratio: calc((100vw - 200px) / (100vh - 100px)))
</code>
</pre>

<p>…but CSS requires <code>X/Y</code> string values for its <code>aspect-ratio</code> queries. Using <code>calc()</code> is right out.</p>

<p>Instead, we have to <strong>reverse-engineer the media query.</strong> Querying the aspect ratio, after all, is just syntactic sugar for crunching the viewport width and height. Like so:</p>

<p class="math">viewport’s aspect-ratio = viewport width ÷ viewport height = 100vw ÷ 100vh</p>

<p>Let’s think about what we want using actual math symbols, instead of CSS’s hecked-up <code>min-</code>/<code>max-</code> system:</p>

<dl class="proof">
  <dt class="math">aspect-ratio ≥ 7/8</dt>
  <dd>We want to know if the viewport’s aspect ratio is greater than or equal to 7/8 (the viewBox’s aspect ratio).</dd>

  <dt class="math">100vw ÷ 100vh ≥ 7/8</dt>
  <dd>Since the viewport’s aspect ratio equals 100vw/100vh, we substitute that.</dd>

  <dt class="math">100vw ≥ 7/8 × 100vh</dt>
  <dd>Multiply both sides by 100vh.</dd>

  <dt class="math">width ≥ 7/8 × 100vh</dt>
  <dd>Since 100vw is the width of the viewport, substitute that back in.</dd>

  <dt><code>min-width: calc(7/8 * 100vh)</code></dt>
  <dd>Convert into CSS syntax.</dd>
</dl>

<p>Now, if that’s all we wanted, I could precalculate the work for everyone’s browsers and use <code>(min-width: 87.5vh)</code>. But I haven’t introduced the chrome’s space requirements yet.</p>

<ol>
  <li>When <code>(orientation: landscape)</code>, the available width = 100vw - 200px and the available height = 100vh - 100px</li>
  <li>Otherwise, the available width = 100vw and the available height = 100vh - 200px</li>
</ol>

<p>So with those complicating factors, what aspect ratio do we really want?</p>

<ol class="proof">
  <li>
    <p>If <code>(orientation: landscape)</code>:</p>
    <dl>
      <dt class="math">aspect-ratio of available space = (100vw - 200px) ÷ (100vh - 100px)</dt>
      <dd>We want to find out if this is larger than 7/8.</dd>

      <dt class="math">(100vw - 200px) ÷ (100vh - 100px) ≥ 7/8</dt>
      <dd>Like this. We need to isolate either the 100vw or the 100vh so we can turn it into the <var>width</var> or <var>height</var> viewport dimension.</dd>

      <dt class="math">100vw - 200px ≥ 7/8 × (100vh - 100px)</dt>
      <dd>Multiply both sides by (100vh - 100px).</dd>

      <dt class="math">100vw ≥ (7/8 × (100vh - 100px)) + 200px</dt>
      <dd>Add 200px to both sides.</dd>

      <dt class="math">width ≥ (7/8 × (100vh - 100px)) + 200px</dt>
      <dd>Subsitute <var>width</var> for 100vw.</dd>

      <dt><code>min-width: calc((7/8 * (100vh - 100px)) + 200px)</code></dt>
      <dd>Convert to CSS syntax. (Now <em>that</em> is an ugly media condition.)</dd>
    </dl>
  </li>

  <li>
    <p>Otherwise:</p>
    <dl>
      <dt class="math">aspect-ratio of available space = 100vw/(100vh - 200px)</dt>
      <dd>Second verse, same as the first. This time the chrome isn’t quite as complicated.</dd>

      <dt class="math">100vw ≥ 7/8 × (100vh - 200px)</dt>
      <dd>Multiply both sides by (100vh - 200px).</dd>

      <dt class="math">width ≥ 7/8 × (100vh - 200px)</dt>
      <dd>Substitute <var>width</var> for 100vw.</dd>

      <dt><code>min-width: calc(7/8 * (100vh - 200px))</code></dt>
      <dd>Convert to CSS syntax.</dd>
    </dl>
  </li>
</ol>

<p>Okay, cool. Now we have the second half of our media conditions. So we need the dimensions of the viewBox for each of these:</p>

<ol>
  <li><code>"(orientation: landscape) and (min-width: calc((7/8 * (100vh - 100px)) + 200px))"</code></li>
  <li><code>"(orientation: landscape)"</code></li>
  <li><code>"(min-width: calc(7/8 * (100vh - 200px)))"</code></li>
  <li><code>""</code></li>
</ol>

<p>Alright, let’s take it from the top.</p>

<ol class="proof">
  <li>
    <p>If <code>"(orientation: landscape) and (min-width: calc((7/8 * (100vh - 100px)) + 200px))"</code>, the viewBox is height-constrained. That means we’ll need the height to figure out the width.</p>

    <dl>
      <dt class="math">viewBox’s height = available height = <code>calc(100vh - 100px)</code></dt>
      <dd>The viewBox will take up the entire height the <code>&lt;svg&gt;</code> element does.</dd>

      <dt class="math">aspect-ratio = height ÷ width</dt>
      <dt class="math">7/8 = <code>calc(100vh - 100px)</code> ÷ width</dt>
      <dd>Since we set the aspect ratio of the viewBox to be 7/8, we can substitute that and the width value we just figured into the aspect ratio equation.</dd>

      <dt class="math">7/8 × width = <code>calc(100vh - 100px)</code></dt>
      <dd>Multiply both sides by <var>width</var>.</dd>

      <dt class="math">width = <code>calc(100vh - 100px)</code> × 8/7</dt>
      <dd>Divide both sides by 7/8.</dd>

      <dt>width = <code>calc((100vh - 100px) * 8/7)</code></dt>
      <dd>Convert to CSS syntax.</dd>
    </dl>
  </li>

  <li>
    <p>If not, and if <code>"(orientation: landscape)"</code>, the viewBox is width-constrained.</p>

    <p>That means the the viewBox will take up all of the width of the <code>&lt;svg&gt;</code> element. Therefore, the width of the viewBox is also <code>calc(100vw - 200px)</code>.</p>
  </li>

  <li>
    <p>If not, and if <code>"(min-width: calc(7/8 * (100vh - 200px)))"</code>, the viewBox is height-constrained.</p>

    <dl>
      <dt class="math">height = <code>calc(100vh - 200px)</code></dt>
      <dd>The height that the <code>&lt;svg&gt;</code> element is taking up.</dd>

      <dt class="math">aspect-ratio = height ÷ width</dt>
      <dt class="math">7/8 = <code>calc(100vh - 200px)</code> ÷ width</dt>
      <dd>Substitute like before.</dd>

      <dt class="math">width = <code>calc(100vh - 200px)</code> × 8/7</dt>
      <dd>I isolated the width variable in one step this time. if you forget how to do it, look back at Step 1.</dd>

      <dt>width = <code>calc((100vh - 200px) * 8/7)</code></dt>
      <dd>Convert to CSS syntax.</dd>
    </dl>
  </li>

  <li>
    <p>Otherwise, it’s width-constrained. This time, there’s no horizontal chrome at all, so the width is just 100vw.</p>
  </li>
</ol>

<p>We’re getting there!</p>

<h4 id="the-image">The image</h4>

<p>Like the viewBox, we’ll use the <code>&lt;image&gt;</code> from last time:</p>

<pre>
  <code class="html">&lt;svg viewBox="0 0 1400 1600" preserveAspectRatio="xMidYMid"&gt;
  &lt;image x="200" y="200" width="1000" height="1200"/&gt;
&lt;/svg&gt;
</code>
</pre>

<p>We’re in the home stretch. Once we get the width values for this final box, we can assemble the <code>sizes</code>.</p>

<p>Unlike before, I’m not going to need the step-by-step equation solving. (If you were feeling patronized, don’t be… those were for <strong>me</strong> to understand what the hell I was doing.) We can take the width values of the viewBox and then multiply those by the percentage of the viewBox the image takes up. Which is…</p>

<p class="math">image-width ÷ viewBox-width = 1000/1400 = 71.42%</p>

<p>Of course, if you remember from way back at the top of this post, we can’t use percentages, so we’ll go with 0.7142 instead. Staple those widths onto the back of the media conditions and voilà:</p>

<ol>
  <li><code>(orientation: landscape) and (min-width: calc((7/8 * (100vh - 100px)) + 200px)) calc((100vh - 100px) * 8/7 * 0.7142)</code></li>
  <li><code>(orientation: landscape) calc((100vw - 200px) * 0.7142)</code></li>
  <li><code>(min-width: calc(7/8 * (100vh - 200px))) calc((100vh - 200px) * 8/7 * 0.7142)</code></li>
  <li><code>71.42vw</code></li>
</ol>

<p>What have I done.</p>

<h4 id="assembling">Assembling</h4>

<p>Putting it all together for the final markup:</p>

<pre>
  <code class="html">&lt;svg viewBox="0 0 1400 1600" preserveAspectRatio="xMidYMid"&gt;
    &lt;switch&gt;
        &lt;foreignObject x="200" y="200" width="1000" height="1200" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"&gt;
          &lt;picture&gt;
            &lt;source srcset="giraffe@0.75x.jpg 300w,
                           giraffe.png        400w,
                           giraffe@1.5x.jpg   600w,
                           giraffe@2x.jpg     800w,
                           giraffe@2.5x.jpg  1000w,
                           giraffe@3x.jpg    1200w,
                           giraffe@3.5x.jpg  1400w,
                           giraffe@4x.jpg    1600w,
                           giraffe@4.5x.jpg  1800w,
                           giraffe@5x.jpg    2000w,
                           giraffe@5.5x.jpg  2200w,
                           giraffe@6x.jpg    2400w,
                           giraffe@6.5x.jpg  2600w,
                           giraffe@7x.jpg    2800w,
                           giraffe@7.5x.jpg  3000w,
                           giraffe@8x.jpg    3200w,
                           giraffe@8.5x.jpg  3400w,
                           giraffe@9x.jpg    3600w,
                           giraffe@9.5x.jpg  3800w,
                           giraffe@10x.jpg   4000w"
                    type="image/jpeg"
                    sizes="(orientation: landscape) and
                           (min-width: calc((7/8 * (100vh - 100px)) + 200px))
                           calc((100vh - 100px) * 8/7 * 0.7142),

                           (orientation: landscape)
                           calc((100vw - 200px) * 0.7142),

                           (min-width: calc(7/8 * (100vh - 200px)))
                           calc((100vh - 200px) * 8/7 * 0.7142),

                           71.42vw"&gt;

            &lt;img src="giraffe.jpg" alt="A giraffe."
                 srcset="giraffe@1.5x.jpg   1.5x,
                         giraffe@2x.jpg       2x,
                         giraffe@2.5x.jpg   2.5x,
                         giraffe@3x.jpg       3x,
                         giraffe@3.5x.jpg   3.5x,
                         giraffe@4x.jpg       4x,
                         giraffe@4.5x.jpg   4.5x,
                         giraffe@5x.jpg       5x"
                 height="400" width="300"&gt;
          &lt;/picture&gt;
        &lt;/foreignObject&gt;

        &lt;image xlink:href="giraffe.png" x="200" y="200" width="1000" height="1200"&gt;
            &lt;title&gt;A giraffe.&lt;/title&gt;
        &lt;/image&gt;
    &lt;/switch&gt;
&lt;/svg&gt;
</code>
</pre>

<p>If it weren’t in the requirements to support photographic images, I could replace <em>all of that</em> with a single <code>&lt;image xlink:href="giraffe.svg"&gt;</code>. But I guess I built character this way.</p>

<h2 id="thats-all-folks">That’s all, folks</h2>

<p>I hope that you don’t have to do what I’m doing, partially because of everything you just saw, but mostly because it won’t make you any money. (<em>Trust me.</em>). But if you run into tricky responsive image situations, hopefully something from this post will guide you a little.</p>

<p>Thanks for sticking with me!</p>

<p>
  <small>(Code for the Web, they said. It’s fun, they said.)</small>
</p>
