Home > Net >  How can I make two divs the same height where one of them has to keep a square aspect ratio?
How can I make two divs the same height where one of them has to keep a square aspect ratio?

Time:11-09

I am creating a responsive grid of images. Each row has two images—one rectangular, and one square—and the layout is reversed for each row (square rectangle -> rectangle square, and so on).

Currently, I am using height: 0; padding-bottom: 100% to make my square div keep its ratio, and the rectangular div gets height: 100%; padding-bottom: 0;. It works completely fine, until there's a case where the last image in the gallery is a rectangular div on its own row. The height: 100%; no longer has any height to work with, so it ends up with no height at all.

I have recreated my issue in this CodePen: https://codepen.io/Dalen_K/pen/GRvdEjp

How can I ensure that the last div maintains the same height that it would have if it had a square next to it (preferably without JS)? Would a grid work better for this than flexbox? If so, how would I go about doing it?

Thanks in advance!

CodePudding user response:

Use this for .image-large and it will be fixed:

&.image-large {
    height: 0;
    padding-bottom: calc(50% - 12px);
  }

And the reason is that column height is decided based on content height or the size of tallest column in the same row. (I mean the visible row that column resides in, not the row tag). Since your col-4 columns have a content with height (which is provided by padding), the other one automatically becomes same as it. In the last row however, the column has no reference height to inherit, and that's why the image inside it can't take more than 50px height which is set as the minimum. What I did is giving the images in large columns a height in a similar manner you gave height to the smaller images. (Extra 12 pixel was there because of 24px gap between columns, that's why I subtracted that)

  • Related