Resize a group of images to match the parent's width and height dimensions

I am working with a div that contains variously-sized images and is nested inside a parent container.

<div id="parentContainer">
<div id="boxToScale">
    <img src="http://placehold.it/350x150" />
    <img src="http://placehold.it/150x350" />
    <img src="http://placehold.it/200x200" />
    <img src="http://placehold.it/50x200" />
</div>
</div>

My goal is to scale #boxToScale so that it fits perfectly inside #parentContainer in terms of both width and height, while still maintaining the aspect ratios of all images inside. The scaling factor should be consistent for all images, and they should remain on the same line.

You can see the current setup on jsfiddle here: http://jsfiddle.net/32sm4/

I have tried to find solutions for scaling multiple images proportionally, but most resources only cover scaling a single image. Since I do not know the exact sizes of the images beforehand, only the size of #parentContainer, I am seeking assistance in achieving this through JavaScript/jquery or CSS if possible. Thank you!

Edit: Here is an example of how I envision the layout after scaling #boxToScale:

Answer №1

Upon reviewing your image, I have updated my answer to better suit the style you are aiming for.

I referenced this jsfiddle.net/7dpHK/2 (commented by charlietfl) which provided a good starting point. However, there were issues with the 4px borders/paddings around the images and some convoluted CSS that needed clarification. To resolve this, you need to calculate the total border size like so:

var border = $("#boxToScale img").length * 4;

Subtract this from the parent width (parentW):

parentW = $box.width() - border

Here is an example of it working correctly.

JS:

var border = $("#boxToScale img").length * 4; // Account for 4px padding around each image
var $box = $('#boxToScale'),
    parentW = $box.width() - border,
    parentH = $box.height(),
    imageTotalW = 0,
    imageTotalH = 0,
    $imgs = $box.children();

$imgs.each(function () {
    var img = $(this),
        ht = img.height(),
        w = img.outerWidth()

    imageTotalW += w;
    img.data('w', w);

});

var img_width_ratio = parentW / imageTotalW;
$imgs.each(function (idx) {
    var $this = $(this),
        $prev = $this.prev();
    $this.width($this.outerWidth() * img_width_ratio);
});

DEMO

JS:

function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
    var ratio = [maxWidth / srcWidth, maxHeight / srcHeight ];
    ratio = Math.min(ratio[0], ratio[1]);

    return { width:srcWidth*ratio, height:srcHeight*ratio };
}

imagesInContainer = $("#boxToScale img").length;

var toWidth = $("#parentContainer").width() / imagesInContainer;
var toHeight = $("#parentContainer").height() / imagesInContainer;

$("#boxToScale img").each(function(){
    var imageWidth = $(this).width();
    var imageHeight = $(this).height();
    var getRatio = calculateAspectRatioFit(imageWidth, imageHeight, toWidth, toHeight);
    $(this).width(getRatio.width);
    $(this).height(getRatio.height);
});

Note: An additional 1px border on images could affect the code. Refer to this example without borders for clarity.

Answer №2

#boxToScale {
border: solid blue 1px;
white-space: nowrap;
}

#boxToScale img {
 width:20%;
 height:auto;
 display:inline-block;
 }

This solution may seem unconventional, but it could be effective. Give it a try and see if it helps.

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

Error: The code has a syntax issue due to an unexpected "function" token while using

Recently, I decided to try out Node version 6.2.1 with some of my code. My goal was to migrate the hyper-callback oriented codes to a cleaner and potentially more efficient approach. Surprisingly, when I attempted to run the node code in the terminal, an ...

What is the best way to display jQuery/AJAX response in a table cell?

I am struggling with a script that retrieves data from a SQL database query and need help placing the result in a specific table cell. Here is the query: <script type="text/javascript"> $(document).ready(function(){ $('.typeval').change(f ...

Passing a return value to ajax success within an Express application

I am trying to retrieve a value from an included file and use it in the success function of an ajax call within Express. Below is my code for app.js: var userdetail = { "useremail":req.body.useremail, "fname" : req.body.fname, "lname" : req.bo ...

Are you planning to print the JSON information?

I've been working on mastering JavaScript and decided to create a script that displays all public Facebook statuses related to a specific keyword. However, things aren't going as planned. You can find a sample URL where the JSON data is located h ...

Unleashing the potential of an endless animation by incorporating pauses between each iteration

I am trying to create an infinite animation using animate css but I want to add a delay between each iteration. After exploring various options, I first attempted to achieve this using plain JavaScript. Here is the HTML snippet: <div id="item" class= ...

Interested in incorporating href within a PHP variable?

My goal is to send a verification email without displaying the link in the email itself. Instead, I want to include text that says "click here to verify." { $verify_email=" Hello, Thank you for signing up. To verify your e-mail, please visit http://".$sit ...

JavaScript Date Validation: Ensuring Proper Dates

I am working with a date string that is in the format of "DD-MM-YYYY" and have successfully validated it using this code: var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-\d{4}/ ; if(!startDate.match(dateFormat)){ alert("'Start Dat ...

Creating a custom jQuery plugin for exporting data

I am crossing my fingers that this question doesn't get marked as 'already answered' because I have thoroughly searched previous questions and unfortunately, my specific case is not listed anywhere. I have successfully created a jQuery func ...

Center text vertically within a Bootstrap anchor element (button)

I am facing difficulty in vertically aligning text within a Bootstrap (3) <a> element while it works fine in a <button> Here is the HTML : <button class="btn">some text<span class="glyphicon glyphicon-play pull-right"></span> ...

How can I incorporate a custom font into my Git Pages website?

Having trouble adding an external font to my GitHub page. The font is in my directory, but I can't seem to get it to work on the page at https://github.com/Aadesh9985/Aadesh9985.github.io I've attempted various methods without success... I came ...

Utilize the withCredentials property in conjunction with $resource

I am looking to utilize a resource with a cookie set in the navigator. Using $http makes it simple, just need to set withCredentials to true: $http({ method: 'POST', url: url, data: user, withCredentials: true }); However, for ...

Assistance needed with Jquery fade-in and fade-out effects

$('.HelpBoxOk').live('click',function() { var currentDiv = $(this).parent().parent().parent().parent().parent().parent(); var shouldFadeInNext = false; if($(this).attr('value') == 'Next') { ...

Aligning labels vertically with inputs

How can I align all my input fields (image) to the same vertical line? I tried using the vertical-align css property and a sass mixin I found (see below), but neither seemed to work. @mixin vertical-align($pos) { position: $pos; top: 50%; -we ...

Creating a versatile menu component: A step-by-step guide

One of my current projects involves designing a menu screen component that must be user-friendly and easily customizable. The component will consist of various options displayed in list form. const options = [ { text: 'Option 1', }, { ...

What is the best way to animate an element to slide down when it is hidden with

I'm working on an html tag called "loginBox" (<loginBox> ... </loginBox>) that is initially hidden with display:none. When a user selects an option, I want it to smoothly slide down instead of just appearing and disappearing. How can I ach ...

Is there a way to remotely access and read text files stored on a server using either JavaScript or Ajax from an IIS6.0 Virtual directory?

Is it possible to use JavaScript or Ajax to read the text from a file on a remote machine (from IIS6.0 Virtual directory) and then copy it into a specific folder on the client machine? ...

Challenges Encountered with Random Image Generator in JavaScript

I am encountering an issue with a script that is supposed to change the default images to a random image each time the page is refreshed. However, I keep receiving an error stating that boxID is null. Why is boxID null? <script type="text/javascript" ...

Once the div content is reloaded using AJAX, the refreshed HTML suddenly vanishes

My JS code reloads the div every 2 seconds: var auto_refresh = setInterval(function() { $('#indexRefresh').load('/includes/index_refresh_include.php?_=' + Math.random()); }, 2000); After that, I have an AJAX request that loads mor ...

Is there a way to terminate an ongoing axios request?

I have been encountering a memory leak issue whenever my browser is redirected away from this component. To resolve this, I tried to cancel it using the cancel token, but unfortunately, it doesn't seem to be working as expected. I am puzzled as to why ...

Troubleshooting issue with node.js 13 import functionality

$ node --version v13.8.0 We will now proceed to create three files: // package.json { "type": "module" } // foobar.js function foo() { console.log('foo') } export default {foo} // index.js import Foo from './foobar ...