Indeed, it is feasible, but only if you have prior knowledge of whether the image is in landscape or portrait orientation. Here's how you can achieve this using HTML:
<div class="wrapper">
<img src="picture.jpg">
</div>
Next, with the help of JavaScript or some server-side magic (although this may go against certain requirements), assign a class to the <img>
element indicating whether it's a landscape
or portrait
image. Then, style it using CSS:
.wrapper {
width: 200px;
height: 200px;
overflow: hidden;
}
.landscape {
height: 100%;
}
.portrait {
width: 100%;
}
It's worth noting that typically such adjustments are made server-side for optimization purposes, ensuring that the browser doesn't have to load a large image unnecessarily. You mentioned concerns about mobile devices (possibly in a comment) regarding JavaScript performance, but the impact on bandwidth is minimal compared to downloading an oversized file.
If needed, you could implement this JavaScript solution (off the cuff) (ensure it runs after DOM content is loaded):
var images = document.querySelectorAll(".wrapper img");
for (var j = 0; j < images.length; j++) {
var picture = images[j];
if (picture.width > picture.height) picture.classList.add('landscape');
else if (picture.width < picture.height) picture.classList.add('portrait');
}
To prevent any flickering, consider initially hiding the images using display: none
and then revealing them in JavaScript once the appropriate classes have been assigned.
This method doesn't significantly impact performance. It leverages the browser's native CSS handling, which is almost as efficient as using getElementById
. While there's no need for dimension calculations at this stage, minor optimizations can be explored:
- Explore more effective loop constructs (exact technique uncertain)
- Omit the
else if
statement and utilize just an else
: enhancing JavaScript speed while slightly compromising CSS efficiency, which is generally acceptable.
- Consider utilizing
className
instead of classList
, delving into nuanced optimization strategies.