My art website features individual pages for each work, most of which are high-resolution photos. In order to optimize the viewing experience, I resize these images to fit the screen, ensuring they take up most of the available space.
The resizing process is tailored to each artwork's shape: square-shaped works fill the vertical space and scale their width accordingly, while tapestry-shaped pieces fill the horizontal space and adjust the height accordingly.
I currently use a Javascript script that calculates and applies the desired dimensions on the image tag's onload event. However, there is a noticeable delay between when the image starts loading and when it resizes, making the page look unattractive during that time, especially on slower internet connections.
Therefore, my inquiry is whether there is a way to achieve this image resizing based on a certain percentage of screen size while maintaining the aspect ratio purely through CSS?
This answer offers an alternative Javascript solution, but I am interested in exploring a CSS-only approach if feasible.
Here is my current scripting approach:
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 > 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 < 540) {
element.parentNode.setAttribute("style","width:" + 540 + "px");
}
else {
element.parentNode.setAttribute("style","width:" + (element.width + 40) + "px");
}
}
}