Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gatsby image fluid stretches to beyond the vertical size of the container

I'm building a gatsby site to show my photographs. I want a full-screen page for each photograph, and the photo should fill out the page, but respecting the aspect ratio.

The problem is that while photos shot in landscape orientation are limited correctly, photos shot in portrait orientation fill out all horizontal space but overflows the vertical space.

In the documentation there is the statement

As mentioned previously, images using the fluid type are stretched to match the container’s width and height

However, my observed behavior is that it only stretches to match the width, not height.

I simplified my problem into this small example, that tries to contain the images in a 400x400px container:

import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
import Img from "gatsby-image"

export default (props) => {
  const { data } = props;
  return (
    <Layout>
      <div style={{height: "400px", width: "400px", background: "white" }}>
        <Img fluid={ data.file.childImageSharp.fluid } />
      </div>
    </Layout>
  )
}

export const query = graphql`
  query($id: String!) {
    file(id: { eq: $id }) {
      childImageSharp {
        fluid(maxWidth: 500, maxHeight: 500, fit: INSIDE) {
          ...GatsbyImageSharpFluid
        }
      }
    }
  }
`;

In the landscape example, the image is constrained to the width of the containing div: Landscape example

In the portrait orientation example, the image fills out the entire width of the containing div, becoming too high:

Portrait orientation example

How do I make Gatsby Image scale down to also be restrained to the available vertical space?

p.s. the rounded corners in the example images are remnants of a bootstrap class from an older solution, but its presence did not affect the problem in question.

like image 921
Pete Avatar asked Jul 24 '20 14:07

Pete


1 Answers

It appears that if I add height and object-fit CSS properties to the <Img /> tag, it works as I intend. (in Firefox and Chrome)

<Img
  style={{ height: "100%", width: "100%" }}
  imgStyle={{ objectFit: "contain" }}
  fluid={ data.file.childImageSharp.fluid }
/>

This gives the intended result, both in my simplified example, but also in the actual flex-box based layout.

like image 129
Pete Avatar answered Nov 09 '22 08:11

Pete