Adjust the height of taller images to match the size of other images within a flexbox grid

On my Wordpress category page, I have a flexbox grid showcasing posts with titles and excerpts. Most images have the same proportions, but a few are significantly taller. I'm looking to responsively set the max-height of the tall images to match the height of the regular images. Each grid item includes an image container with the class imageThumb.

(function($) {
 $('.imageThumb img').each(function() {
    var maxHeight;
    var width = $(this).clientWidth;    // Current image width
    var height = $(this).clientHeight;  // Current image height

    // Check if the current width is larger than the max
    if(width > height){
        maxHeight = $(this).clientHeight;
        console.log(maxHeight)
    }

    // Check if current height is larger than max
    if(height > width){
        $(this).css("height", maxHeight);   // Set new height
    }
});

})(jQuery);

I'm aware that the (width > height) comparison may output too many heights. It's not possible to individually target images for their heights due to the dynamic nature of the blog's content.

Here is the CSS related to this issue.

.imageThumb {
  overflow: hidden;
}

.imageThumb img {
  width: 100%;
}

I've explored various solutions such as setting fixed width and height for the images, but the site owner prefers a scaling effect as the window size increases. I've also attempted absolute positioning within a container, but it didn't yield the desired results. Any suggestions on the best approach to tackle this dilemma would be greatly appreciated.

Thank you for your assistance!

Answer №1

Hey there, I'm not completely sure if I've got it right, so please share your link if I'm mistaken.

On another note, I believe this code should do the trick:

let maxHeight = 0;

$('.imageThumb img').each(function(){
   let thisHeight = $(this).height();
   if (thisHeight > maxHeight) { maxHeight = thisHeight; }
});

$('.imageThumb img').height(maxHeight);

Cheers!

Answer №2

Through the guidance of Daebak Do and some modifications, I was able to find the correct solution. The key was setting the maximum height of the container imageThumb to maintain the same width as other pictures, preventing distortion for taller images. If the picture ends up being cut off too much, you can experiment with the commented code provided.

var maxHeight = 0;

$('.imageThumb').each(function(){
   var thisH = $(this).height();
   if (thisH > maxHeight) { 
    maxHeight = thisH;
    $('.imageThumb').css('maxHeight', maxHeight);
    //may need to change to the following if pics are getting cut off too much
    // $('.imageThumb img').css('maxHeight', maxHeight);
    // // $('.imageThumb img').css('width', 'auto');

     }
});

The initial code didn't cover all the requirements, so I also utilized the following code below. Any feedback is appreciated!

var imageThumb = document.getElementsByClassName('imageThumb');
var arr=[];
var tallArr=[];
//add all items to an array
$(".imageThumb").each(function(){ arr.push($(this));});
//filter out all items that are taller than they are wide
arr.filter(function(obj){
  if(obj.context.clientHeight > obj.context.clientWidth) {
    tallArr.push(obj);
  } 
});


//loop through the items that are tall and add a new class to them
for (i = 0; i <= tallArr.length; i++) {
  $(tallArr[i]).addClass('bigHeight'); 
}
//gets first item that has a normal height and grabs it's height value
var normalHeight = arr[0].context.clientHeight;
//change css of bigHeight

//sets bigHeight equal to normalHeight
$('.bigHeight').css('max-height', normalHeight);

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

Enhance your SVG image in D3 by incorporating a drop-shadow effect

Trying to apply a drop-shadow effect to an SVG image using D3. Check out my code below and see the example block here: var imgurl = 'http://www.logo-designer.co/wp-content/uploads/2015/08/2015-Penn-State-University-logo-design-4.png'; var mar ...

Position images on the right side of text within the container

I'm having trouble aligning the Facebook and Google+ icons on my website, which can be found here. These circular icons are located just below the navigation bar at the top of the page. The navigation bar is part of a class called 'container_head ...

What is the best way to position a bigger character directly above a smaller container?

My goal is to center a single character, using CSS, in a span that is smaller than the character itself. The setup I have is: <span id="A">X</span><span id="B">Y</span><span id="C">Z</span> All three spans are styled ...

Using jQuery to replace an HTML element multiple times

Seeking assistance for implementing functionality that replaces a button with an input field, where users can enter information and hit enter. Once the action is completed, the original button should reappear. The current script works effectively but lacks ...

Adjust the height of the div element to match the screen height with AngularJS controller

Can someone please assist me in resolving this issue? I'm currently working on a div element that displays data (positioned on the left side of the screen). I want to add a scrollbar exclusively to this div. I managed to achieve this by using the fol ...

What is the best way to implement a date range filter in AngularJS for a specific year or month?

I am just starting to learn AngularJS. I have a date formatted as follows: d MMM y. However, I have two fields - one called "from" and the other "to" - that should act as filters for the date range, based on a year range or month range. Here is how I am or ...

What is the best way to trigger a jQuery UI dialog using an AJAX request?

My website includes a jQuery UI Dialog that opens a new window when I click the "create new user" button. Is there a way to open this window using an AJAX request? It would be useful if I could open the dialog-form from another page, such as dialog.html ...

Display and conceal different sections using hyperlinks

Hey there, I'm back with another issue related to this code snippet on jsfiddle: https://jsfiddle.net/4qq6xnfr/9/. The problem I'm facing is that when I click on one of the 5 links in the first column, a second div appears with 3 links. Upon clic ...

I'm experiencing difficulty accessing the correct identification number for my questions on the website

Hi, I'm currently developing a website using Meteor where users can post questions and receive answers. I want to implement a feature that allows users to delete their own questions. When I try to directly pull the ID of the question and delete it, it ...

adjust the webpage to be optimized for the size of the screen

Looking to adjust the webpage layout so that it fits perfectly on the screen without the need for vertical or horizontal scrolling. Additionally, we want the image to be centered. See below for the current code snippet: #copyright { top: 0px; right: ...

Tips for updating a database value based on a textbox value using AJAX or PHP

<?php include('db_connection.php'); $id = $_GET["id"]; if(isset($_POST['user'])) { $user=mysql_real_escape_string($_POST['user']); $query=mysql_query("SELECT * FROM customers WHERE username ...

Unleash the power of jQuery Fix by utilizing this slider multiple times on a single page

I'm facing an issue with reusing a slider multiple times using jQuery. The current implementation only works for one slider, as they all share the same ID. I need a solution to make each slider independent. I've tried using methods like .closest ...

How to connect Kendo UI Grid column headers with a JSON data source

Currently, I am working with a Kendo UI grid and my goal is to dynamically bind the column headers to a JSON file instead of hardcoding it in the controller. Is there a way to achieve this similar to how we bind data using the dataSource? If not, what wo ...

What could be causing the image not to be centered inside the <table><td>?

Currently, I am developing a web application with Google Script that generates a dashboard featuring multiple tables. To design the layout, I am utilizing Bootstrap (https://cdn.jsdelivr.net/npm/[email protected] /dist/css/bootstrap.min.css). Despite ...

Deleting the chosen list item from an unordered list

I'm having some trouble removing the selected item with the class "selected" from my list using jQuery. Instead of just deleting the LI item, the entire list is getting cleared out. Here's a quick fiddle I created to demonstrate the issue: http ...

Explore a Wordpress HTML code

I own a WordPress website using the Photolux theme. My desire is to extract HTML elements such as titles and tags, but for some reason they are not visible. Just to clarify, I am not interested in reading the XML format. If anyone has any suggestions or ...

JavaScript - Hover function not functioning properly

Having some difficulty with the .hover() function I am fetching dribbble shots that are displayed on page load. However, I am experiencing issues when trying to add a class via hover on these shots. Interestingly, the hover functionality works perfectly ...

"Encountered an unexpected token in Javascript - jsp error

Recently, I started working on a JSP application and encountered an issue with passing URL variables from a servlet to a JSP page using request.getattribute. When trying to pass the data to a JavaScript function, we received the following error: Uncaught ...

Adjust the parent element to match the width of the child by utilizing the "display: grid" property

edit: I'm uncertain if this is a duplicate issue. My concern is not about the background color extending beyond the container width, but rather about expanding the container to match the size of its child with display: grid. I have updated the example ...

A Guide to Importing CSV Data Into a Datatable

Is there a way to efficiently import data from a CSV file and display it in a table using the datatables plugin? Currently, I have a fixed table structure: <table id="myTable" class="table table-striped" > <thead> ...