Automatically adjust image size to fit the screen (without using JavaScript)

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");
        }
    }
}

Answer №1

When using the vw and vh units in CSS, you have the flexibility to size elements based on the browser viewport rather than their parent containers.

To ensure that an image does not exceed the size of the browser viewport on any device, set the max-width and max-height properties for the image element as shown below:

#image-id {
    max-width: 80vw;
    max-height: 80vh;
}

Answer №2

Instruct your images to fill up the width of their container up to a maximum of 100%, while maintaining their aspect ratio by setting the height to auto.

.image-container {
  max-width: 100%;
  height: auto;
}

Answer №3

Have you considered implementing the background-size: cover; property in this case? Each image could serve as the background for a div, with specific attributes configured as follows.

  • height
  • width
  • background-size: cover;
  • background: url('image.png') center center no-repeat;

Answer №4

When it comes to scaling images, JavaScript is often recommended as the best solution. However, if you're insisting on using only CSS, consider utilizing percentages instead of pixel values. This way, your images will scale appropriately within a specified container.

.img {
max-width:100%;  
max-height:100%;

}

If you're interested in learning more about resizing images proportionally with CSS, check out this question and answer on StackPost.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to alter the height of the element

I am attempting to resize an element by dragging, similar to this example. I have created a simple directive for this purpose: @Directive({ selector: '[drag-resize]' }) export class DragResizeDirective { private dragging: boolean; const ...

Uploading files with previews and no option to alter the image dimensions

I am having trouble with resizing an image preview before submitting it. Despite setting the width and height to 1px in both the div and image, it still displays at its normal dimensions. $(function() { var imagesPreview = function(input, placeToIns ...

Angular's Motion Module

Incorporating Angular-5 into my project has introduced a plethora of animations on various pages. While the utilization of jQuery provides a straightforward approach for adding and removing classes to DOM elements, it is frequently advised against using jQ ...

Creating a carousel with three thumbnails arranged in two rows

Currently, I am using a slider for my thumbnails. If you want to check out the code for this thumbnail slider, click on this link: thumbnails slider code My goal is to display 6 thumbnails in total, with 3 thumbnails shown in each row (2 rows total). Add ...

Refresh an HTML table dynamically without the need to reload the page or manually click a button by leveraging

As a beginner in PHP, I am looking to update the HTML table automatically when inserting a list of data using SQL commands in XAMPP. This is the code snippet from `index.php` that retrieves data from the database and displays it in the table. `<?php ...

creating and managing multiple redirect routes in vue.js application

const router = new VueRouter({ routes: [ {path: '*', redirect: '/'} } )} I have configured this as the default redirect route in my routes.js file. Now, I am wondering how I can set multiple redirect paths and trigger them ...

Designing a rounded border radius for various child elements within a layout

I am currently working on creating a circular container that houses an image and a description overlaid at 50% opacity. Here is what I have achieved so far: https://i.stack.imgur.com/pIkO1.png My goal is to apply a uniform border-radius to the entire div ...

How to Use Jquery to Select a Checkbox within a Table

Within my project, I have a table setup like this: <table id="filter-table" class="table table-striped"> <thead> <tr> <td>Accessory</td> <td>Typology</td> <td>Check</td> < ...

Creating a Dynamic Navigation Bar with CSS and JavaScript

I have encountered an issue with my responsive menubar where the dropdown button does not have any style when clicked. function myFunction(){ var x = document.getElementById("myMenubar"); if (x.className === "menubar"){ x.className += "responsiv ...

Creating a dynamic text design using Bootstrap or CSS: What's the best approach?

I attempted to enable responsive font sizes in Bootstrap 4.3.1 by setting the $enable-responsive-font-sizes variable to true, but I did not see any changes. Below is the code from my template.html file: <div class="m-2" id="role" ...

HTML's Inheritance Concept

Imagine having multiple HTML pages with identical headers and footers. Is there a way to store the header and footer in a single file that can be inherited by each page, eliminating the need for repetition? Are there alternative methods to avoid duplicatin ...

What steps should I take to successfully integrate my Dojo DataGrid into a Dojo ContentPane that is nested within a Dojo TabContainer?

It seems that the issue arises from having different settings for parseOnLoad in the separate widgets. I have experimented with both true and false values but without success. To troubleshoot, I created three web pages - two containing TabContainer and Dat ...

Experience the full functionality of Google Maps API without the need for jQuery or PHP with PanTo

I'm not a developer and I find myself stuck in the panTo() function. All I want is to execute this function with an if-else statement without having to reload the Google Map or using jQuery. <body> <div id="map"></div> <d ...

The issue with jqTransform not displaying the select box value on a hidden contact form

Could really use some assistance here and apologize if it's a hassle: Link to contact form To view the contact form, simply click the "Contact" button in the top left corner. The jqTransform jQuery plugin is being used to style it. Initially, it&apo ...

Aligning elements in the center vertically using absolute positioning for multiple elements

I have been experimenting with a method to vertically center an element in a div that has unknown height. You can check out the approach I used here: In my case, I am working with anchor tags and this solution was particularly helpful due to the position ...

Tips for designating all content within a <div> element to open in a blank target (target="_blank")

I am looking to open all content within a specific <div> in a new tab (target="_blank"). I am open to any solution, whether it involves JS, CSS, HTML, classes, IDs, etc. I experimented with using <base target="_blank">, but it affect ...

Custom WordPress Popups

I have implemented a custom popup on my WordPress website and it works fine when tested on a simple `index.html` file on the local server. However, when I embed the code in the `header.php` and `style.css` files of WordPress on the local server, the popup ...

HTML5 - Transforming your webpages into interactive flipbooks

Is there a way to achieve a page-turn effect when loading external HTML pages into a div? I am interested in utilizing CSS3, HTML5 or jQuery for this purpose. ...

Eliminate a specific segment from a webview using Swift

Looking to create a webView app in Swift for my website at , but struggling to remove the navigation bar from the web page. I've attempted to remove it by ID, but haven't had any success. class ViewController: UIViewController { @IBOutlet w ...

Using jQuery to toggle visibility on click within WordPress

Looking for a way to make three buttons change color on hover and display different content when clicked? You're not alone! Despite searching through tutorials and forums, the solution remains elusive. The buttons are structured like this: <div i ...