首页 > 解决方案 > 如何使流体Img组件小于其容器元素

问题描述

我在这里( https://www.gatsbyjs.org/packages/gatsby-image/#avoiding-stretched-images-using-the-fluid-type )读到我应该能够使 Gatsby 组件保持在其最大宽度即使它小于父容器元素的宽度。我相信我了解他们在文档中提供的代码示例中发生了什么,但是当我尝试将其调整为我的代码时,图像仍然会拉伸以填充容器宽度。

他们的代码:

// in React component
const NonStretchedImage = props => {
  let normalizedProps = props
  if (props.fluid && props.fluid.presentationWidth) {
    normalizedProps = {
      ...props,
      style: {
        ...(props.style || {}),
        maxWidth: props.fluid.presentationWidth,
        margin: "0 auto", // Used to center the image
      },
    }
  }

  return <Img {...normalizedProps} />
}

注意: GatsbyImageSharpFluid 片段不包括presentationWidth。您需要将其添加到您的 graphql 查询中,如以下代码段所示:

{
  childImageSharp {
    fluid(maxWidth: 500, quality: 100) {
      ...GatsbyImageSharpFluid
      presentationWidth
    }
  }
}

我的代码:

// in React component
<Img
      fluid={data.myImage.childImageSharp.fluid}
      alt="description"
      fadeIn={true}
      style={{
        ...(props.style || {}),
        maxWidth: props.fluid.presentationWidth,
        margin: "0 auto", // Used to center the image
      }}
    />

// in GraphQL query
myImage: file(relativePath: { eq: "imageName.jpg" }) {
      childImageSharp {
        fluid(maxWidth: 400) {
          ...GatsbyImageSharpFluid_withWebp
          presentationWidth
        }
      }
    }

标签: gatsby

解决方案


有时,添加!important到您的 CSS 规则可以解决问题。还要检查内部呈现的页面 HTML 输出developer console。他们倾向于创建大量嵌套的 html,从而阻止您的 css 按预期工作。


推荐阅读