No, this is not possible - conditional statements cannot be processed using HTML or CSS, but you must do this using JS.
An example would be calculating (and possibly saving for future use) the aspect ratio of an image to determine if it is in landscape or portrait mode:
$(document).ready(function() { $("img").each(function() { // Calculate aspect ratio and store it in HTML data- attribute var aspectRatio = $(this).width()/$(this).height(); $(this).data("aspect-ratio", aspectRatio); // Conditional statement if(aspectRatio > 1) { // Image is landscape $(this).css({ width: "100%", height: "auto" }); } else if (aspectRatio < 1) { // Image is portrait $(this).css({ maxWidth: "100%" }); } else { // Image is square $(this).css({ maxWidth: "100%", height: "auto" }); } }); });
See the fiddle here - http://jsfiddle.net/teddyrised/PkgJG/
Update 2019 : As ES6 becomes the de facto standard, the above jQuery code can easily be converted to vanilla JS:
const images = document.querySelectorAll('img'); Array.from(images).forEach(image => { image.addEventListener('load', () => fitImage(image)); if (image.complete && image.naturalWidth !== 0) fitImage(image); }); function fitImage(image) { const aspectRatio = image.naturalWidth / image.naturalHeight;
div.wrapper { background-color: #999; border: 1px solid #333; float: left; margin: 10px; width: 200px; height: 250px; }
<div class="wrapper"> <img src="http://placehold.it/500x350" /> </div> <div class="wrapper"> <img src="http://placehold.it/350x500" /> </div> <div class="wrapper"> <img src="http://placehold.it/500x500" /> </div>
However, if all you need to do is make sure that the image is placed in a container of arbitrary size, simple CSS will work:
div.wrapper { background-color: #999; border: 1px solid #333; float: left; margin: 10px; width: 400px; height: 400px; } div.wrapper img { width: auto height: auto; max-width: 100%; max-height: 100%; }
<div class="wrapper"> <img src="http://placehold.it/500x350" /> </div> <div class="wrapper"> <img src="http://placehold.it/350x500" /> </div> <div class="wrapper"> <img src="http://placehold.it/500x500" /> </div>
Terry source share