Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Auto-sizing Images to Fit a Div - Making the CSS Work</strong></p> <p>Here is one way of doing it, start with the following HTML:</p> <pre><code>&lt;div class="container portrait"&gt; &lt;h4&gt;Portrait Style&lt;/h4&gt; &lt;img src="http://placekitten.com/150/300"&gt; &lt;/div&gt; </code></pre> <p>and the CSS:</p> <pre><code>.container { height: 300px; width: 240px; background-color: red; float: left; overflow: hidden; margin: 20px; } .container img { display: block; } .portrait img { width: 100%; } .landscape img { height: 100%; } </code></pre> <p>and the demo fiddle: <a href="http://jsfiddle.net/audetwebdesign/QEpJH/">http://jsfiddle.net/audetwebdesign/QEpJH/</a> </p> <p>When you have an image oriented as a portrait, you need to scale the width to 100%. Conversely, when the image is landscape oriented, you need to scale the height.</p> <p>Unfortunately, there is no combination of selectors in CSS that targets the aspect ratio of the image, so you can't use CSS to pick out the correct scaling.</p> <p>In addition, you have no easy way of centering the image since the top left corner of the image is pinned to the top left corner of the containing block.</p> <p><strong>jQuery Helper</strong></p> <p>You can use the following jQuery action to determine which class to set based on the aspect ratio of the image.</p> <pre><code>$(".container").each(function(){ // Uncomment the following if you need to make this dynamic //var refH = $(this).height(); //var refW = $(this).width(); //var refRatio = refW/refH; // Hard coded value... var refRatio = 240/300; var imgH = $(this).children("img").height(); var imgW = $(this).children("img").width(); if ( (imgW/imgH) &lt; refRatio ) { $(this).addClass("portrait"); } else { $(this).addClass("landscape"); } }) </code></pre> <p>For each image in <code>.container</code>, get the height and width, test if <code>width&lt;height</code> and then set the appropriate class.</p> <p>Also, I added a check to take into account the aspect ratio of the containing block. Before, I had implicitly assumed a square view panel.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload