【问题标题】:Gatsby image fluid stretches to beyond the vertical size of the containerGatsby 图像流体延伸到容器的垂直尺寸之外
【发布时间】:2020-11-14 10:00:20
【问题描述】:

我正在建立一个 gatsby 网站来展示我的照片。我希望每张照片都有一个全屏页面,并且照片应该填满页面,但要尊重纵横比。

问题在于,虽然横向拍摄的照片受到正确限制,但纵向拍摄的照片会填满所有水平空间,但会溢出垂直空间。

the documentation中有声明

如前所述,使用流体类型的图像会被拉伸以匹配容器的宽度和高度

但是,我观察到的行为是它只会拉伸以匹配宽度,而不是高度。

我将我的问题简化为这个小例子,它试图将图像包含在一个 400x400px 的容器中:

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
        }
      }
    }
  }
`;

在横向示例中,图像被限制为包含 div 的宽度:

在纵向示例中,图像填满了包含 div 的整个宽度,变得太高了:

如何使 Gatsby Image 缩小以也限制在可用的垂直空间内?

附言示例图像中的圆角是旧解决方案中引导类的残余,但它的存在并不影响所讨论的问题。

【问题讨论】:

  • 你希望图片是 400px x 400px 吗?
  • 不,这只是为了举例说明图像在纵向时拉伸到容器外部,但在横向时保留在容器内。不过,我似乎已经想通了

标签: gatsby gatsby-image


【解决方案1】:

看来,如果我将 heightobject-fit CSS 属性添加到 &lt;Img /&gt; 标记,它会按我的意图工作。 (在 Firefox 和 Chrome 中)

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

这给出了预期的结果,无论是在我的简化示例中,还是在实际的基于 flex-box 的布局中。

【讨论】:

    猜你喜欢
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 2015-10-18
    • 2011-10-08
    • 1970-01-01
    • 2012-02-15
    相关资源
    最近更新 更多