1

EDIT: My question is about how to style img elements with CSS without stretching the image (altering aspect ratio) so that they have a consistent height and width in a grid, without the use of divs.

EDIT2: The suggested duplicate question does not answer my question. I accepted the answer about the CSS clip-path property since it most closely matched my needs.

I'm trying to create a 3x3 image gallery. I got the widths to work correctly, but I can't figure out how to get the images to be the same height without explicitly setting a height in pixels (which stretches the images, doesn't adapt to the user's screen size, and looks horrendous).

Here's what I have so far (only showing 2 rows to demonstrate height difference)

This is the goal

I've found a few answers on Stack Overflow which use divs with background images to solve the problem, but the images I'm using are content so they need to be included in my HTML as img elements.

Here is my HTML (not including src and alt img attributes for simplicity):

<section>
  <img>
  <img>
  <img>
  <img>
  <img>
  <img>
  <img>
  <img>
  <img>
</section>

Here are my styles for the img elements:

section img {
  width: 100%;
  display: block;
  margin: 1em 0;

  @include for-tablet-up {
    display: inline-block;
    margin: .5em 2.5%;
    width: calc(85%/2);
  }

  @include for-desktop-up {
    width: calc(85%/3);
  }
}

Here are my Sass mixins:

@mixin for-tablet-up {
    @media screen and (min-width: 768px) { @content; }
}

@mixin for-desktop-up {
    @media screen and (min-width: 1024px) { @content; }
}
  • 1
    A quick Internet search brought me to [this article](https://medium.com/@chrisnager/center-and-crop-images-with-a-single-line-of-css-ad140d5b4a87), which uses [`object-fit: cover`](https://developer.mozilla.org/de/docs/Web/CSS/object-fit) (a rule I didn't even know about, but can also be found in one answer to [this possible duplicate question](https://stackoverflow.com/questions/493296/css-display-an-image-resized-and-cropped)). Would that be a solution? – domsson Dec 15 '17 at 05:27
  • The absolute best way is to make sure the images are the same size to start with. – Nathaniel Flick Dec 15 '17 at 05:42
  • @NathanielFlick I'm pulling in photos from the Unsplash API, so I can't control their dimensions. – Daniel Hughes Dec 15 '17 at 06:58
  • 1
    @domsson From what I can tell, the object-fit property requires the img to have a set height. The answers to the question you linked work if you can make use of divs, but don't work if you're just trying to style an img element. – Daniel Hughes Dec 15 '17 at 07:37
  • Oh, I see. Too bad, but thank for sharing your insights! – domsson Dec 15 '17 at 15:25

1 Answers1

0

The CSS clip-path property sounds like it would fit your needs.

echristo66
  • 198
  • 1
  • 14