Using flexbox to evenly distribute images with borders and padding to ensure consistent height

Currently, I am utilizing jQuery to adjust the flex-grow value of a wrapper div based on the aspect ratio of a figure's image. This approach was suggested here.

However, once I apply a border and padding to the figure, the images no longer retain the same height. Is there a way to factor in the border and padding when calculating to ensure all the images are of equal height? Or is there an alternative method to achieve consistent height for these figure images?

The disparity becomes evident when removing the border and padding from the figure CSS, resulting in all figure images having uniform height.

EDIT: Upon further observation, it appears that this issue presents differently in Chrome. While Firefox displays the content almost accurately, Chrome portrays the images at varying sizes!

$(document).ready(function() {
  $('div.pack').css({
      "display": "flex"
    })
    .children().each(function() {
      $(this).css({
        "width": "100%"
      });
      var $img = $(this).find('img');
      var aspect = $img[0].naturalWidth / $img[0].naturalHeight;
      $(this).wrap('<div style="display:flex; flex: 0% ' + aspect + ' 1;" />')
      $img.css({
        "width": "100%",
        "height": "auto"
      })
    });
});
figure {
  padding: 4px;
  border: 1px solid lightgray;
  margin: 0;
}

div.pack>div:not(:last-child) {
  margin-right: 1%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='pack'>
  <figure>
    <img src="http://via.placeholder.com/300x300">
    <figcaption>Big caption here Big caption Caption here </figcaption>
  </figure>
  <figure>
    <img src="http://via.placeholder.com/300x500">
    <figcaption>Caption here</figcaption>
  </figure>
  <figure>
    <img src="http://via.placeholder.com/600x150">
    <figcaption>Caption here</figcaption>
  </figure>
</div>

Answer №1

By adding an extra wrapper to the figures, you're causing the issue. Avoid wrapping the figures in <div> tags and everything should function as anticipated.

However, on smaller devices, the captions may become too tall due to wrapping. My recommendation is to utilize a @media query to display them full width on mobile devices. Since you are applying style attributes directly, using !important will be necessary to implement your @media query for flex.

$(window).on('load', function() {
  $('div.pack').children().each(function() {
    let img = $(this).find('img')[0], 
        asp = img.naturalWidth / img.naturalHeight;
    $(this).css({
      flex: asp + ''
    })
  });
});
figure {
  padding: 4px;
  border: 1px solid lightgray;
  margin: 0;
  font: italic normal 14px/normal serif;
}

div.pack>figure:not(:last-child) {
  margin-right: 1%;
}

figure img {
  width: 100%;
  height: auto;
}

.pack {
  display: flex;
}

@media (max-width: 560px) {
  .pack {
    flex-wrap: wrap;
  }
  .pack figure:not(#duh) {
    flex: 1 0 auto !important;
    max-width: calc(100% - 10px);
    margin: 0 0 10px;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='pack'>
  <figure>
    <img src="http://via.placeholder.com/300x300">
    <figcaption>Big cap tion Caption here Big cap tion Capt ion here </figcaption>
  </figure>
  <figure>
    <img src="http://via.placeholder.com/300x500">
    <figcaption>Caption here</figcaption>
  </figure>
  <figure>
    <img src="http://via.placeholder.com/600x150">
    <figcaption>Caption here</figcaption>
  </figure>
</div>


Note: I am puzzled by why flex: 0% x 1;, which translates to:

flex-grow: 0%;
flex-shrink: x;
flex-basis: 1;

produces the same outcome as flex: x;, interpreted correctly as:

flex-grow: x;
flex-shrink: 1;
flex-basis: 0%;

However, considering potential cross-browser/device issues, I have reverted it back to its original form.

I have also shifted the entire script from document.ready to the window.load event to ensure it only runs after all <img> elements have loaded.


Lastly, utilizing Firefox for frontend development has a couple of drawbacks:

  • Its development tools consistently lag behind Chrome by a few months.
  • Firefox has a smaller market share compared to Chrome, meaning you might need to fix issues for a larger portion of users during cross-browser testing. It may be more efficient to prioritize Chrome compatibility first.

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's causing the excessive amount of white space in my image?

Whenever I include a picture of myself on the page, it creates excessive white space at the bottom. I'm not sure why this happens, but removing the image eliminates the white space. I've attempted adjusting the margins and padding, as well as se ...

Using jquery to loop through JSON objects based on their values

Looking to display the NBA Western Conference leaders by seed, I have utilized the JSON file available at: http://data.nba.com/data/v2014/json/mobile_teams/nba/2014/00_standings.json Here is the current setup: $(document).ready(function() { $.getJSON( ...

Modifying Font Style in Angular 4 Material

Is there a way to change the font in Angular 4 Material material.angular.io using the styles file in .CSS format instead of SASS? While the documentation offers an example for SASS at: https://github.com/angular/material2/blob/master/guides/typography.md ...

How can I use variables to show the second dropdown list only when a value has been selected in the first dropdown?

Is there any way I can choose a specific value from a dropdown list and based on that selection, show another dropdown list? I understand how to do it with regular words, but what if I use variable names? University Name: <select name="university" id=" ...

I am in need of a efficient loader for a slow-loading page on my website. Any recommendations on where to find one that works

I'm experiencing slow loading times on my website and I'm looking to implement a loader that will hide the page until all elements are fully loaded. I've tested several loaders, but they all seem to briefly display the page before the loader ...

Ensuring Unique CSS for Diverse Devices: A User-Agent Driven Approach

I am facing multiple challenges and working towards finding solutions. I have developed a webpage and now I want to redirect the link to the CSS file based on the user agent. `<script type="text/css" src="style.css"> </script>` However, inst ...

The JavaScript code is not functioning properly on the server after the ajax request

I have a situation where an ajax request is sending data to a PHP file, and then the PHP file is generating HTML content with some JavaScript code. The JavaScript code includes Google's chart library, but unfortunately the chart is not working as inte ...

What is the best way to display form input fields depending on the selected value?

I've been struggling with a seemingly simple issue that I can't seem to find the right solution for, even after scouring Google. I have a form field for input and a select field with various values, including an "Other" option. Here's what ...

Is JSDOM able to handle media queries?

I understand that JSDOM may not have all the features of a full-fledged browser, but there is mixed information out there about its CSS support. While I've personally seen it parse CSS, responsive styles don't seem to function as expected. Can an ...

What steps can I take to improve the design of this layout created using Twitter Bootstrap?

Currently, I am designing a sample form layout using Twitter Bootstrap. The form displays fields horizontally, with a link between each field. My goal is to have bullet points appear on the right side of the fields when the link is clicked. However, the al ...

Pattern matching for CSS class names

My current project involves creating a PHP function that will sift through CSS and JS files, swapping out class names and IDs in CSS selectors without touching the HTML elements or CSS properties themselves. Alas, my knowledge of regular expressions is sev ...

When trying to access Tumblr images following a jQuery request, a 403 Forbidden response is encountered

I've been working on putting together a Tumblr site that can auto paginate, use colorbox integration, and load tagged elements with jQuery.ajax. After successfully retrieving the JSONP response and parsing it, I encountered an issue when trying to ap ...

The functionality of displaying a loading image when the Upload button is clicked has encountered a glitch and

I am looking to add a feature that displays a loader when a user uploads a file by clicking on a button. The loader should be visible while the data is being processed in the background. To achieve this, I have included a div as shown below: <div id=" ...

Refresh DataTable while making a fetch request

Here is the HTML code snippet where I want to apply DataTable: <div id="reportrange" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc;"> <span></span> </div> <table id=" ...

Prevent user input in calendar view using HTML classes

Need help adding a date picker to my code. Below is the snippet of code: The issue I am facing is that I want to prevent users from manually typing in dates. <div class="form-group clearfix"> <label class="col-lg-4 control-label">Date Sold ...

Combining an image and a link in HTML CSS: Tips for stacking elements on top of each other

I am currently working on adding a hyperlink to an image, so that when the image is clicked it will navigate to the specified link. However, I am having trouble with the formatting of the hyperlink as it is appearing smaller than the actual image. Below ...

`Is it possible to animate the rotation of an image within an input control?`

After coming across this helpful answer, I successfully added a rotating GIF image as an icon inside an INPUT control on its right side. Simply applying the "busy" class to my control did the trick, and now it looks like it's in progress. input.busy { ...

What are the steps to create two frames using Twitter Bootstrap?

I'm just starting to work with Twitter Bootstrap and I need some help. Can someone assist me in creating a two-column layout inside the HTML, where the menu in the header stays visible even when scrolled down? I've included my HTML code below. Th ...

jQuery - Trouble with loading a different image source

** UPDATE ** An image demonstrating the required action. By clicking on an unapproved (x) comment, it should automatically approve and change to a check mark, and vice versa. I have implemented the following jQuery code, however, I am encountering issues ...

What is the best way to integrate a notification system using jQuery?

I am looking to create a notification area that will refresh whenever a new message is sent using jQuery or Ajax (my database is stored in a soap server). I want to make a soap call every few seconds to achieve this, but I'm not sure how to go about i ...