Determining the aspect ratio of an image is essential in using flexbox to achieve consistent heights

Recently, I came across a fascinating code pen titled: this demonstration of equal responsive height images

I am determined to make sure that all images have the same height, regardless of their width/height variances. The CSS displayed below utilizes flexbox with flex to attain this result: https://i.sstatic.net/17RkQ.png

/* Crucial details for this particular demo. */

img {
  width: 100%;
  height: auto;
  vertical-align: middle;
}

.pics_in_a_row {
  display: flex;
}

.img1 { flex: 1.3344; } /*  <-- how do I determine this value? */
.img2 { flex: 1.3345; }
.img3 { flex: 0.7505; }
.img4 { flex: 1.5023; }
.img5 { flex: 0.75; }

I am puzzled about calculating the flex value. Is it related to aspect ratio?

Answer №1

The ratio of width to height for the image is referred to as the aspect ratio.

For example, if an image is 600 pixels wide and 800 pixels high, the aspect ratio would be calculated as 600/800=0.75

Understanding this concept allows you to select one of the methods outlined in the article that was mentioned:

When using CSS, there are several ways to define the aspect ratio:

  • Determine the aspect ratio manually and input it directly into the CSS code (as shown in this example)
  • Utilize CSS's calc() function to compute the aspect ratio (e.g. flex: calc(600/800);)
  • Employ a preprocessor to calculate the aspect ratio during the build process

Answer №2

Dealing with this issue myself was a bit of a challenge. You can determine the image ratio by dividing its width and height. If you're not using JavaScript, simply grab your calculator and divide the image width by its height. However, if you are using JavaScript, to find the flex value, you'll need to divide the image's width by its height, like so:

const imageRatio = img.naturalWidth / img.naturalHeight;

When obtaining the value, make use of the naturalWidth and naturalHeight properties that provide the original image size. Initially, I only used height and width; however, these values may be incorrect in certain cases (such as during image loading).

https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/naturalWidth

In my case, I opted to calculate the column widths using JavaScript instead of the flex property since it doesn't function properly when text is present within the column. This made the calculations more intricate. You have to calculate the ratio of all images, sum them up to get the total ratio, and then divide the individual image ratios by this overall ratio to obtain the percentage.

Here's some sample pseudocode:

const getFullRatio = (images) => images.reduce((acc, curr) => (curr.naturalWidth / curr.naturalHeight) + acc, 0);

const containerWidth = 740;
const columnAmount = images.length;
const columnMargin = 15;
const marginPercentageToAdd = ((columnAmount * columnMargin) / containerWidth) + 1;
const fullRatio = getFullRatio(images);
const fullRatioWithMargins = fullRatio * marginPercentageToAdd;

 images.forEach((img) => {
    const imageRatio = img.naturalWidth / img.naturalHeight;
    const columnRatio = (imageRatio / fullRatioWithMargins) * 100;

    const imageParentDiv = img.closest('.COLUMNCLASS');
    imageParentDiv.style.width = `${columnRatio}%`;
    const image = img;
    image.style.width = '100%';
});

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

Navigating the FormSpree redirect: Tips and tricks

I recently set up my website on Github Pages and wanted to integrate a free contact form from FormSpree. However, I encountered an issue where after submitting the form, it redirected to a different website, which was not ideal. After researching online, I ...

Have you ever wondered why Vue 3 imports all JS files for every page upon the initial project load?

Is there a way to make Vue 3 import only the necessary js files for each component instead of loading all files at once when the project is first loaded? For example, if I navigate to the contact page, Vue should only import the contact.js file, rather tha ...

Encountering the "Local resource can't be loaded" error when attempting to link a MediaSource object as the content for an HTML5 video tag

I'm attempting to make this specific example function properly. Everything runs smoothly when I click the link, but I encounter an error when trying to download the HTML file onto my local machine and repeat the process. An error message pops up sayi ...

CSS - Revealing an element on the backface post flip animation

I encountered an issue while working on a CSS flip card project. Despite using backface-visibility: hidden;, one element remains visible from the other side. In the simplified snippet provided, if you click on more in the bottom right corner, the card fli ...

"Place text at the center of a div that is rotated

I'm facing the challenge of centering a heading both vertically and horizontally within a div that has been rotated 45 degrees (transform:rotate(45deg);). Due to this rotation, I have attempted to counteract it by rotating the heading in the opposite ...

Stylesheets per module in Angular 2

For my website design, I've decided to adopt a modular structure using sass. To ensure consistency throughout the module, instead of defining stylesheets at the component level, I plan to define them at the module level and import them into each compo ...

Using CSS :active can prevent the click event from firing

I've designed a navigation menu that triggers a jquery dialog box to open when a link is clicked. My CSS styling for the links includes: .navigationLinkButton:active { background:rgb(200,200,200); } To attach the dialog box, I simply use: $("#l ...

There seems to be a malfunction in the functionality of my Django template navbar

Within my project, I am utilizing two templates named base.html and contact.html. The contact.html template extends the base.html template, and these are the only two templates in use. When I navigate to the blog or about section by clicking on them, the p ...

Submitting an ajax form with the use of the symbol '&'

I am currently working on a form submission using the .ajax() method. Within my script, I have the following code: data: dataString, The variable dataString is composed of: var list = $('.listsummary').val() The listsummary class is assoc ...

issue with border color staying the same when focusing

I've been struggling with changing the border on focus in my code. Despite trying various methods, nothing seems to be working. Can someone help me figure out what I'm doing wrong? <input type="text" spellcheck="false" data-placement="top" id ...

Javascript is not functioning properly when making an ajax call

Having a bit of trouble with JavaScript not working after an Ajax call. Everything functions normally until new data is fetched from the database or an Ajax call is made. The issue seems to be that the JavaScript doesn't load properly. Any help would ...

Transforming react.js into HTML and CSS programming languages

I have a small experiment I need help with. As I am not familiar with react.js, I would like to convert my main.jsx file into pure HTML/CSS/JS without using react. The issue I'm facing is how to handle form data submission to the server in vanilla HTM ...

Using three.js to set the HTML background color as clearColor

How can I set the HTML background as clearColor using three.js? Here is the code snippet for three.js: // Setting up the environment var vWebGL = new WEBGL(); var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(75, window.innerWidth / ...

struggling to insert submit button within input field in bootstrap 4.3.1

Currently, I am working with Bootstrap 4.3.1 and I have been attempting to place a submit button inside an input field. I have tried various methods from StackOverflow but haven't found a solution yet. Since my input has the class rounded-pill, it is ...

The chosen choice is not able to be shown within the option tag

When attempting to filter options using JavaScript based on a selected item, I'm encountering issues. If the selected element contains 'CONTINUE' or 'BRACKET', it should be split into an array by space and only the first two indice ...

What is the best method for automatically closing the modal window?

I implemented a modal window on my website. Within the modal, there is a green button labeled "Visit" which triggers the "Bootstrap Tour". I aim for the modal to automatically close when the tour starts. To access this feature on my site, users need to ...

When you hover over the vertical sidebar menu in Bootstrap material design, a submenu will appear

Looking to create a three-column display that functions as one submenu when hovering over each menu item? <div class="container"> <div class="row"> <div class="col-sm-4"> <ul class="vertical-nav"> <li>&l ...

Selenium WebDriver: The challenge of using visibilityOfElementLocated when the element is not actually visible

I've encountered an issue with the Firefox Webdriver where it fails to accurately determine if an element is visible. Here is the code I am using, which incorrectly indicates that the element is visible: wait.ignoring(UnhandledAlertException.class).u ...

``In Internet Explorer, the function to swap the image source when hovering over the parent element

I'm trying to make it so that when I hover over the parent (Li) tag with my mouse, the src attribute of the child img tag changes. This code works correctly in Chrome but not in Firefox and Internet Explorer. <li class="player"> . . //some c ...

The process of making an image fill an entire div using Html and CSS

What is the best way to make an image fill an entire div using Html and CSS? ...