Maintaining responsiveness, CSS grid will automatically adjust the height of each element to be equal

I am facing an issue with my grid layout. Each element in the grid has an image and other divs below it. The problem arises when the screen size changes, causing the elements to scale automatically due to responsive width. I want all the images to have the same height while maintaining this responsiveness, similar to YouTube. How can I achieve this?

Here is a snippet of my grid:

JSX:

<div className="home-container">
  {elements.map((el) => (
    <Element el={el}></Element>
  ))}
</div>

CSS:

.home-container {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 20px;
  margin-left: 250px;
  grid-auto-rows: 1fr;
  grid-row-gap: 30px;
}

This is how each element card is structured:

JSX:

<div className="element-container">
   <div className="element-img">
      <img src={imageUrl} alt={title} />
   </div>
   <div>...</div>
   <div>...</div>
</div>

CSS:

.element-container {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  height: fit-content;
  border-radius: 10px;
  overflow: hidden;
}

.element-img {
  display: flex;
  margin-bottom: 20px;
}

.element-img > img {
  width: 100%;
  height: 100%;
  border-radius: 20px;
  object-fit: cover;
}

Issue: The problem occurs when the grid is resized as the aspect ratio of the images is not maintained consistently across all elements.

https://i.sstatic.net/ILZ57.gif

Answer №1

Overview

  1. To maintain the aspect ratio of an image, create a wrapper around it using position: relative; and set a padding-top that defines the aspect ratio.

  2. Position the image within the wrapper by setting position:absolute;. Use object-fit: cover; to retain the aspect ratio while covering the container. Set width:100%; and height:100%; to fill the container.


Implementation

.home-container {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 20px;
  margin-left: 250px;
  grid-auto-rows: 1fr;
  grid-row-gap: 30px;
}

.element-container {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  min-height: 250px;
  border-radius: 10px;
  overflow: hidden;
}

.element-img {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 */
  margin-bottom: 20px;
}

.element-img > img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 20px;
}

The padding-top in .element-img maintains the image's aspect ratio by creating an invisible box based on the specified ratio. It adapts responsively, ensuring the correct proportions regardless of the element's width.


Aspect Ratio Guidelines

  • Widescreen (16:9) = 56.25%
  • Standard (4:3) = 75%
  • Square (1:1) = 100%
  • Photography (3:2) = 66.66%
  • Ultrawide (21:9) = 42.85%

You can calculate the aspect ratio percentage using:

(Height / Width) * 100

For example, for 16:9 aspect ratio:

56.25 = (9/16) * 100

Feel free to adjust the percentage to best suit your design needs.


Demonstration

.grid-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  padding: 20px;
}

.grid-item {
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.aspect-ratio-16-9 {
  position: relative;
  width: 100%;
  padding-top: 56.25%;
}

.aspect-ratio-16-9 img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="grid-container">
  <div class="grid-item">
    <div class="aspect-ratio-16-9">
      <img src="https://via.placeholder.com/300x169" alt="300x169 Image">
    </div>
  </div>
 
  [Additional grid items with different image sizes]
 
</div>


References

Explore these resources for further insights on implementing and understanding aspect ratios in web design:

Answer №2

To achieve equal-height columns using CSS grid, ensure all items in a row are set to the height of the tallest column by employing the rule grid-auto-rows: 1fr;. For uniform column widths, employ the rule grid-template-columns: 1fr 1fr 1fr; and specify fractional values matching the number of columns.

Example in HTML:

<div class="grid">
    <div>A</div>
    <div>A<br>B<br>C</div>
    <div>A<br>B</div> 
</div>

CSS styling:

.grid {
    display: grid;
    grid-auto-rows: 1fr;
    grid-template-columns: 1fr 1fr 1fr;
}

.grid > div:nth-child(1) {
    background-color: #f97171;
}
.grid > div:nth-child(2) {
    background-color: #f99e50;
}
.grid > div:nth-child(3) {
    background-color: #f5d55f;
}

Answer №3

One way to establish a predetermined height for the image container with the class element-img is by using the following CSS:

.element-img {
  margin-bottom: 20px;
  height: 100px;
}

Answer №4

@C-Gian I have successfully maintained uniform image height while retaining aspect ratio in a flexible grid layout:

  1. To achieve this, I utilized the properties height: 0 and padding-bottom in percentage for .element-img.
  2. I removed the height: 100% declaration from .element-img > img.
  3. The updated CSS for .element-img is as follows:
.element-img {
  display: flex;
  margin-bottom: 20px;
  height: 0;
  padding-bottom: 100%; /* Maintain aspect ratio */
}

By implementing these changes, all images within the flex container will maintain equal height while preserving their original aspect ratios.

I trust that you find this information useful.

Please see my image results below:

https://example.com/image1.gif

https://example.com/image2.gif

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

Using window.open and appending a new feature to it

Below is the code found in my index.html file: <!DOCTYPE html> <html> <head> <script> function createDialogBox() { var dialogBox = window.open("in1.html"); dialogBox.nameBox= "my little box" } window.onload = createDialogBox; wind ...

Three fixed position divs arranged horizontally side by side

I am attempting to organize 3 divs in a row using Flex. ISSUE 1: The div that is centered is set with position: fixed. However, the two other divs on each side do not stay aligned with the centered fixed div when scrolling. If I change the centered div to ...

Issues concerning date and time manipulation - Library Moment.js

As a beginner in JavaScript, I've been working on an activity that generates a table of train times based on user input. However, I'm facing issues with formatting the arrival time correctly. Whenever I input the arrival time in military format ( ...

Can you explain how to utilize theme values in CSS within Mui?

Working on my React app with mui themes, I have the following in index.js: let theme = createTheme({ palette: { primary: { main: "#00aaa0", contrastText: '#fcf4d9', }, secondary: { main: "#D55B3E&quo ...

The placeholder text is not displaying with bullets in Internet Explorer. However, it is functioning correctly in Chrome

I need assistance displaying the placeholder text in IE8 as shown below: "Any relevant reference numbers, such as Direct Debits: - Name of the Branch (if applicable) - What was the original problem - Date the problem occurred " While it appears correct ...

Is Your Mobile Site Displaying Differently?

Although my resume website looks great on Desktop, I recently noticed that the HTML paragraph tags do not scale correctly when viewed on various mobile web browsers (refer to the images attached below). Screenshot 1: Website displayed in Facebook Messenge ...

Utilizing jQuery to modify the text output from an input form

Check out the preview site at . It's a test version before launching on a separate domain. Hello, I need to customize the error response for a CRM contact form integrated into Wordpress with the help of StackOverflow. The form is connected via JavaSc ...

Using jQuery, locate identical text and assign a class to the corresponding container

How can I check if any of the h2 elements match the text in h1, ignoring case sensitivity? If a match is found, I want to add a class to the container Product-div. <div id="PageHeader"> <h1>Same text</h1> </div> <div class= ...

Trick to keep horizontal element alignment intact when scroll bar appears

Currently, all my pages are designed with the standard fixed-width-margin-left-right-auto layout. .container{ width:900px; margin:0 auto; } An issue arises when some of these pages exceed the height of the window, requiring a vertical scroll ba ...

tips for creating dynamic visual effects using CSS on filtered images

img:hover{ -webkit-filter: grayscale(100%); -moz-filter: grayscale(100%); filter: grayscale(100%); } This CSS code snippet will convert the image from color to grayscale upon hovering. However, I am looking to achieve this effect with a smooth animation ...

Steps for deactivating tab stops on the primary webpage in the presence of a snackbar

On my web page, there are multiple drop-down menus, input fields, and buttons that can be interacted with using both the tab key and mouse. After entering certain data, I trigger a snackbar (source: https://www.w3schools.com/howto/howto_js_snackbar.asp) t ...

Javascript AppendChild Problem with Internet Explorer

When it comes to this particular snippet of code, everything seems to run smoothly in Firefox and Chrome. However, Internet Explorer is causing some major headaches. var anotherDiv= document.getElementById("anotherDiv"); var destination = document.getElem ...

Centered alignment with floating divs of abbreviated length

My HTML file has a structure similar to the following: <div style="float:right"> A line of text, floating to the right </div> <div style="text-align:center"> And here, several lines of<br /> text which should be centered. </div& ...

Having trouble making an HTML5 video work on Android? It seems to play fine when clicking the play button,

It has come to my attention that html5 video on Android devices is unable to autoplay. Currently, the video only plays on the device when the user manually clicks on the play button. <video width="640px" height="360px" src="media/video/Moments_of_Every ...

Executing Basic Calculations Instantly with Live Data in Qualtrics

I am encountering an issue with displaying the values on a slider in Qualtrics. I need to show the value where the respondent has placed the handle, as well as the complementary value from the other end of the scale. For example, if the user has chosen 55, ...

How can an object be utilized within the image tag's src attribute?

Is it possible to use an object in the img src attribute? // HTML <img src= "item.img" https://i.sstatic.net/m8PDy.png ...

Tips for building a modal box with HTML, CSS, and jquery!

Looking to create a modal box using HTML, CSS, and jQuery? <button id="myBtn">Click here to open the Modal</button> This code will help you achieve that: <!-- This is the Modal content --> <div class="modal-content"> <sp ...

Unable to remove the most recently added Object at the beginning

I am currently working on a project to create a dynamic to-do list. Each task is represented as an object that generates the necessary HTML code and adds itself to a div container. The variable listItemCode holds all the required HTML code for each list it ...

Adjust the image dimensions within the DIV container

I am currently working on creating my personal portfolio website. I have encountered an issue where the image inside a div element enlarges the size of the entire div as well. My goal is to keep the image slightly larger while maintaining the same size for ...

What steps can I take to create a responsive jQuery UI buttonset?

I am currently facing a challenge with my web app (http://www.tntech.edu/cafe-menu.php) which is being iframed into a mobile application developed by ATT. The button sizes vary on different phone models, and I am seeking a solution to make them responsiv ...