Making two images of different sizes have the same height and completely fill the width of their parent container

I need help making two images in a parent element with a width of 'col-9' have equal heights and fill the width. The images can vary in size, so I'm looking for a simpler solution than using Flex and calculating aspect ratios every time. I am working with Bootstrap 4.

You can see an example of what I currently have below, but I want to find a way to achieve this without having to adjust the flex ratio based on each image's dimensions:

<div class="col-9">
    <div class="d-flex w-100">
        <img src="https://via.placeholder.com/400x600" alt="" class="" style="flex:.666667;">
        <img src="https://via.placeholder.com/300x600" alt="" class="" style="flex:.5;">
    </div>
</div>

Answer №1

In situations like these, I find that utilizing flexbox works best.

Here is an example of how you can implement it:

.parent {
  display: flex;
  flex-flow: row;
}
.child {
  background: #ddd;
}
.child img {
  width: 100%;
  height: 100%;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

<div class="col-9">
  <div class="parent">
    <div class="child">
      <img src="https://cdn.pixabay.com/photo/2014/06/03/19/38/board-361516_1280.jpg"/>
    </div>
    <div class="child">
      <img src="https://cdn.pixabay.com/photo/2016/09/04/11/51/checklist-1643781_1280.png"/>
    </div>
  </div>
</div>

Answer №2

<div class="col-md-9">
    <div class="image-wrapper" style="display: flex;">
        <img src="https://example.com/image1.jpg" alt="" style="margin-right: 10px;">
        <img src="https://example.com/image2.jpg" alt="">
    </div>
</div>

Answer №3

I encountered a similar challenge where I needed to display multiple images with varying aspect ratios to occupy the full width of the page or container while ensuring they all have the same height: https://i.sstatic.net/pc9BF.png

TL;TR

I discovered 2 CSS-only solutions for this issue:

  1. Utilizing padding and margin properties to maintain a constant aspect ratio of elements Source:

Set the width of an element as a percentage (e.g., 100%) of the parent's width, then set the element's padding-top (or -bottom) as a percentage to achieve the desired aspect ratio.

  1. Using flexbox for responsive equal-height images while preserving their aspect ratios Source: https://codepen.io/blimpage/pen/obWdgp

Assign the flex property of each image's wrapper div to the image's aspect ratio (width divided by height).

Both solutions require prior knowledge of the image sizes to implement suitable CSS adjustments. This can be achieved through server-side scripts like PHP, which offers functions like getimagesize() for such tasks.


Details

Solution 1. A pure CSS approach using the padding attribute with detailed explanations:

  • W - page/container width.
  • H - block with images width (constant for all).
  • w0[i], h0[i] - original size of ith image.
  • w[i], h[i] - displayed size of ith image with h[i]=H.

The calculations involve determining ratios, summing up these values, and deriving the aspect ratio for the entire container, among other steps.

An illustrative PHP code example is provided for clarity.

Solution 2. A variant using flexbox that also requires server-side knowledge of image sizes for inline CSS generation:

  • W - page/container width.
  • H - block with images width (same for all).
  • w0[i], h0[i] - original size of ith image.
  • w[i], h[i] - displayed size of ith image.
  • r[i]=w0[i]/h0[i]=w[i]/h[i] - image's aspect ratio.
  • h[i]=H - images should have identical heights.

This solution involves setting the flex property of each image's wrapper div based on the image's aspect ratio to dynamically adjust image widths.

A PHP sample demonstrates how this can be implemented effectively.

Both approaches offer insights into handling equal-height images responsively while maintaining their aspect ratios intact.

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

Loading an image from Vue.js and Django

I'm currently working on a project using Vue, and I'm fetching an image through a Django REST API. The code in table.vue file: <tbody> <tr v-for= "user in users" :key="user.id_users"> <th>{{user.id_use ...

How do you identify a Selenium element using a CSS selector?

Having trouble locating the element for "Sign out" button in Selenium. I've tried using the following CSS identifier: css= div[class='sub-nav chat-bubble']>ul>div:nth-child(3)>li:nth-child(4)>a Could someone please help me modi ...

Can you identify the missing piece in my design?

#container { width: 250px; margin: 0 auto; } .group { border: 1px solid grey; margin-bottom: 20px; } .group p { text-align: center; font-family: Helvetica sans-serif; font-size: 25px; color: #2e3d49; } .group img{ wid ...

Having trouble getting CSS "::Before" to work in my HTML code - any solutions?

I've been struggling to make use of the ::before pseudo-element in CSS for a hover effect. Despite going through various tutorials on YouTube, I can't seem to get it to work properly. I'm not sure why this isn't working as expected. ...

JavaScript allows for the immediate termination of CSS animations

I am currently working on an input box that has a CSS animation applied to it. This animation creates a smooth fade-in effect when the page is loaded. Here is the CSS code: #search-box { /* ... */ animation: 2s fade-in } @keyframes fade-in { ...

Ensure that the table tag in testWeb(jspackage.JSAssignmentDiscount) contains exactly 3 rows and assess whether it complies with the CSS criteria for tables and table rows

Criteria: The table must include the product name, product price, and season information. The product name and product price should be input text boxes labeled with name and price respectively. The season selection should be a dropdown menu labeled with s ...

Exploring the Impact of 2 HostBindings on Class Generation from Inputs in Angular 4

I'm struggling with the code in my component, which looks like this: @Component({ selector: "home", templateUrl: "./home.html" }) export class Home { constructor() {} @HostBinding("class") @Input() public type: string = "alert" @HostBindi ...

What is the way to retrieve an array property in a typescript interface?

Imagine a scenario with three interfaces structured as follows: registration-pivot.ts export interface RegistrationPivot { THead: RegistrationPivotRow; TBody: RegistrationPivotRow[]; } registration-pivot-row.ts export interface RegistrationPivotR ...

Excessive Expansion of Website Width

Initially, I crafted a website on my local server, and it had the ideal width. Afterwards, I uploaded it to the live server and made some design modifications. To my surprise, there is now an unexpected scroll bar at the bottom of the page, causing the s ...

"Implementing form validation in a React application using Bootstrap displays error messages preemptively

I am facing an issue with the code for form validation in React. The error message is appearing for all fields before hitting the submit button. I want the error message to be displayed only when I click on a particular box, and then the corresponding erro ...

Ways to identify and differentiate various checkboxes using HTML and CSS

I am currently working on implementing a thumbs-up and thumbs-down feature, where clicking on the thumb-up icon will change the color to green, and clicking on the thumb-down icon will change it to red. However, I am facing some difficulties understanding ...

Using the scroll feature within the tooltip component in React with @material-ui/core/Tooltip can cause the entire page to

I am currently working with a tooltip created using the @material-ui/core/Tooltip library, and it is functioning correctly. You can see an example of the tooltip in action at this link: https://codesandbox.io/s/kgccc. https://i.stack.imgur.com/fMgGb.png ...

design and construct a three-dimensional shelving unit

After much searching and failed attempts, I am determined to create a stationary cube-shaped bookcase using CSS. Can anyone offer some guidance on how I can achieve this? I have included an image of the design I want to replicate. Thank you .scene { ...

The fill layout in Next.JS Image isn't working properly

According to the Next.js image component documentation, it states: "When fill, the image will stretch both width and height to the dimensions of the parent element, usually paired with object-fit." However, in reality, the image fills the entire ...

Using HTML and CSS to evenly align text in individual sections

Is it possible to recreate the exact look and feel of a justified page from a book or article online using HTML/CSS? This would include replicating the text justification with precise line breaks and setting the outer wrapper width to match the min/max-wid ...

Trouble with AngularJs 1.x causing Bootstrap4 menu toggle collapse to malfunction

Issue with Navbar toggle menu not closing properly. I have attempted the solutions provided here and others in an effort to fix this bug. However, none of them seem to work for me. Here is a snippet of my code: <nav class="navbar navbar-expand-lg ...

Opera's extra space feature allows users to comfortably browse the

I'm attempting to insert a progress bar inside a td element within my table. Below is the code: <td style="width: 150px;"> <div style="height: 16px; max-height: 16px; overflow: hidden; border: 1px solid #80C622;"> < ...

Text in a class button that is not skewed

I crafted a button for my website using a CSS class, aiming for a parallelogram shape by utilizing the skew function. The code worked like a charm, giving the button the desired shape. However, I encountered a dilemma where the text inside the button also ...

Is it possible to customize the arrow on a drop-down menu?

Here is an example of the page I am facing issues with: If you look at the right side of the bottom bar, you will notice a selection option for different themes. I have been attempting to replace the down arrow with an image. Below is the code I have used ...

Error Starting Bootstrap 4 with NPM

I am currently in the process of learning how to automate various tasks related to web development using npm scripts. Displayed below is the contents of my package.json file: { "name": "confusion", "version": "1.0.0", "description": "This particula ...