title: css - Automatically resize image to fit on screen (without Javascript)
body: <p>So, I have an art website, with each work getting its own page. The works are mostly photos, meaning they have higher resolutions than most screens are capable of displaying - so they need to be resized down to scale, obviously.</p>
  
  <p>To make works easier to look through, I display them such that they take up most of the screen (minus 100px in either dimension), scaling to fill whichever dimension is more limiting:</p>
  
  <ul>
  <li>Work X is square-shaped, and on the average monitor it gets resized so that its height fills the entire vertical space, and its width scales accordingly - preserving the aspect ratio</li>
  <li>Work Y is tapestry-shaped, and gets resized so that its width fills the entire horizontal space, and its vertical space gets resized to match that aspect ratio.</li>
  </ul>
  
  <p>I'm currently using a straightforward Javascript script for this, calling a function on the <code>img</code> tag's <code>onload</code> (as well as whenever the window is resized) to calculate the desired width/height of the image and apply that. <em>The problem</em> with using Javascript for this is that there's a delay between when the image begins to load and when it resizes, which makes the page look really ugly for a while, especially when viewing the site on a poor internet connection.</p>
  
  <p>Leading to my question: <strong>is there a way to resize images to a certain percentage of screen size, while preserving aspect ratio, in pure CSS?</strong></p>
  
  <p><a href="https://stackoverflow.com/questions/22450361/automatic-image-resizing-to-fit-screen">This answer</a> provides another Javascript solution, but I'd prefer to find a way to do this in pure CSS if possible.</p>
  
  <hr>
  
  <p>My current script is this:</p>
  
  <pre><code>function setGoodHeight (element) {
      if( on mobile ) {
          ...
      }
      else {
          height_buffer = 100
          width_buffer = 100
          height_diff_pct = element.naturalHeight / window.innerHeight
          width_diff_pct = element.naturalWidth / window.innerWidth
          if(height_diff_pct &gt; width_diff_pct) {
              var h = element.naturalHeight;
              var w = element.naturalWidth;
              element.height = window.innerHeight - height_buffer;
              element.width = w * element.height / h;
          }
          else {
              var h = element.naturalHeight;
              var w = element.naturalWidth;
              element.width = window.innerWidth - width_buffer;
              element.height = h * element.width / w;
          }
          if(element.width &lt; 540) {
              element.parentNode.setAttribute("style","width:" + 540 + "px");
          }
          else {
              element.parentNode.setAttribute("style","width:" + (element.width + 40) + "px");
          }
      }
  }
  </code></pre>