Transforming a static grid into a dynamic responsive grid

I've successfully set up a fixed grid that you can view here: http://jsfiddle.net/challenger/UxzCa/1. The project has two key requirements:

  • Photos should be adjusted to perfectly fit within a square card div (even if width and height vary);
  • The card dimensions must not be rigidly defined.

One possible solution is to utilize jQuery to dynamically adjust widths and heights upon the window.resize event. Are there any other methods available?

Answer №1

I have found a solution that addresses both the image aspect-ratio problem and the fixed-width issue.

To ensure the grid has a fixed width, you can set the width: auto property so that the floats wrap to multiple lines if needed:

.grid-row {
    width: auto;
    margin: 0 auto;
}

To make sure the images scale correctly based on their aspect ratio, create two classes:

.table-cell img.portrait {
    height: 100%;
}
.table-cell img.landscape {
    width: 100%;
}

Then, utilize this jQuery method to apply the correct class depending on each image's aspect ratio:

$('.table-cell').each(function(){
    var image = $(this).find('img');
    aspectRatio = image.height()/image.width();
    if (aspectRatio > 1) 
    {
        image.addClass('portrait');
    }
    else
    {
        image.addClass('landscape');
    }
});

View Demo Fiddle

Additional Note

You may also explore CSS techniques similar to those discussed in the following question to make the .card elements responsive while maintaining their aspect ratio:

How do you vertically center absolute positioned text w/o declaring container size and w/o JS?

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

What is the best way to turn off HTML codes of varying sizes?

I am looking to disable certain HTML code in a specific size. For example, I would like to disable or modify a div with the class "container" when it is 576px wide. Here is a snippet of my code: <link rel="stylesheet" href="https://maxcdn.bootstrap ...

The JavaScript Data table fails to display any data

Why is the first row in my datatable showing as 'No Data'? (document).ready(function() { $('#callback_table').DataTable({ "paging": "input", "ajax": { "type": "GET", ...

Unusual issue with IE 7 when using a fixed width absolute table header

Struggling once again with IE7 on this particular issue. I have created a fixed header scrollable body table primarily using CSS, with horizontal scrolling requiring javascript. It is a modified version inspired by this example. The design appears satisfa ...

script locate the div ID within a given text and clear its content

My string contains some dynamic HTML with a div element having an id of "time", Here's an example: myString = "<div class="class">blahblah</div><div id="time">1:44</div>" How can I generate a new string that is identical to ...

Sinon.js: How to create a mock for an object initialized with the new keyword

Here is the code that I am working with: var async = require('async'), util = require('util'); var Parse = require('parse/node'); function signup(userInfo, callback) { var username = userInfo.username, email ...

Utilize a JavaScript array to showcase particular HTML divisions

With my HTML page using Django, I have a table that contains checkboxes: {% for o in obj %} <input class='germ_ids' name='{{o.id}}'> {% endfor %} <script> var elements = document.getElementsByClassName("germ_id ...

Grouping an array of arrays of objects

I am trying to group an array of objects based on the value of the first item below: const data = [{"value":"value1","metric":1},{"value":"value1","metric":2},{"value":"value3","metric":0},{"value":"value2","metric":4},{"value":"value3","metric":1},{"va ...

Step-by-step guide on how to load an Ext JS tab after clicking on it

I have an Ext JS code block that creates 4 tabs with Javascript: var tabs; $(document).ready( function() { fullscreen: true, renderTo: 'tabs1', width:900, activeTab: 0, frame:true, ...

What could be causing this error to appear when using Next.js middleware?

The Issue at Hand Currently, I am in the process of setting up an authentication system using Next.js, Prisma, and NextAuth's Email Provider strategy. My goal is to implement Next.js middleware to redirect any requests that do not have a valid sessio ...

Leveraging the content delivery network for react-select in a react.js project

I'm having trouble using react-select with cdn. I attempted to download the cdn for react-select but keep encountering an error stating that 'select is not defined'. I also tried downloading the zip package for react-select, but I am unsure ...

Using AngularJS to iterate over an array with a string index using ng-repeat

Is it possible to use ng-repeat to iterate over an array with a string index? Review the sample code snippet below: The following code is within a controller. $scope.days = ["mon", "tue", "wed" .... "sun"]; $scope.arr = []; $scope.arr["mon"] = ["apple"," ...

How to disable the Rubber/Elastic scrolling feature on your iPad?

On my webpage, there is a combination of vertical and horizontal scrolling. Everything works fine when the user swipes left or right exactly, but issues arise when the swipe is not precise along a straight line (diagonally). In this case, both vertical and ...

Oops! Next.js Scripts encountered an error: Module '../../webpack-runtime.js' cannot be located

Looking to develop an RSS script with Next.js. To achieve this, I created a script in a subfolder within the root directory called scripts/ and named it build-rss.js next.config.js module.exports = { webpack: (config, options) => { config.m ...

Clear all form fields upon successful ajax completion

Struggling to reset all input fields in a form after a successful Ajax request. Take a look at the code below: $.ajax({ type: "POST", url: "form.php", data: datos, success: function() { $(&a ...

Ensure that the table row filter continues to function properly even after dynamic content changes have been

I've implemented the following code to filter table rows based on text entered in an input textbox (using a solution found on this link). var $rows = $('#deviceInfoTable tr'); $('#searchVehicleName').keyup(function() { ...

Adjust the browser zoom level to default when navigating to a new page

My mobile site uses ajax to load pages, and I'm looking to implement a feature that resets the zoom level when a page changes. Is there an effective way to detect if a user has zoomed the view while browsing a page? Currently, I have been able to ch ...

Error: The function req.checkBody is missing, despite the presence of the bodyparser and expressvalidator module

When I try to use req.checkBody in my code, I keep getting an error saying it's not a function. I have already included express-validator and body-parser in my project. Here is the snippet of my code: var express = require('express'); var ...

Obtaining solely the words found within HTML documents

In my Python 2.7 project, I have a folder containing multiple HTML pages that I need to extract only words from. My current process involves opening the HTML file, using the Beautiful Soup library to extract text, and then writing it to a new file. However ...

Achieve immediate feedback without delaying for asynchronous function

As I develop an API to handle requests and execute a complex function using Puppeteer, I am faced with the challenge of not wanting the API to wait for the function to finish before sending a success response since it is primarily a submit API. The curren ...