Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to fit an image to borders and keep aspect ratio in HTML
    primarykey
    data
    text
    <p>A problem: there is a table with two cells. And two images in each cell. I need to fit these images to borders and keep aspect ratio. If there is a landscape-orientation image, it should fit to left and right borders. If there is a portrait-orientation image, it should fit to top and bottom borders.</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;Test page&lt;/title&gt;&lt;/head&gt;&lt;body&gt; &lt;script type="text/javascript"&gt; function func(imgname){ var img = document.getElementById(imgname); if(img.height &gt;= img.width) { img.style.height = "100%"; img.style.position = "relative" img.style.width = "auto"; }else{ img.style.width = "100%"; img.style.position = "relative" img.style.height = "auto"; } } function rsz(imgname){ alert('resize '+imgname) } &lt;/script&gt; &lt;center&gt;&lt;table width="80%" height="90%" cellpadding="0" cellspacing="5" border="1"&gt; &lt;tr&gt; &lt;td width="50%" height="80%" onclick="alert('pic 1') " id="td1" &gt;&lt;center&gt; &lt;img id="imgL" onload="func('imgL');" src="http://img.yandex.net/i/www/logo.png" /&gt; &lt;/center&gt;&lt;/td&gt; &lt;td width="50%" height="80%" onclick="alert('pic 2') " id="td2" &gt;&lt;center&gt; &lt;img id="imgR" onload="func('imgR');" src="http://t2.gstatic.com/images?q=tbn:ANd9GcROiXx6BaNBDTn4xAS8FBMH7qUZIOPKcXZKL6asl4hHw2ys-h8Z" /&gt; &lt;/center&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/center&gt;&lt;/body&gt;&lt;/html&gt; </code></pre> <p>There are two small pictures: yandex logo, it's landscape-oriented image (width>height) and image of one person from South Park (it was the first portrait-oriented image which I found in google). Its height is greater than width. If javascript function has no effect( try to insert "return;" in the beginning), both images are small and are in the centers of table cells. But if javascript function works, it has effect ONLY on landscape-oriented images. So we can see Yandex logo fitted to left and right as I want, but the right picture is not fitted to top and bottom. And here is a problem.</p> <p>Thanks.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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.
 

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