gatsby - 如何使流体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
}
}
}
解决方案
有时,添加!important
到您的 CSS 规则可以解决问题。还要检查内部呈现的页面 HTML 输出developer console
。他们倾向于创建大量嵌套的 html,从而阻止您的 css 按预期工作。
推荐阅读
- javafx - 在 FXML 中创建一个空的 VBox,然后在 javafx 中添加节点不起作用
- python - 用 spacy 对文档进行 Lemmatize?
- kubernetes - 如何将守护程序集转换为种类部署
- javascript - document.querySelectorAll() 在找到特定元素后改变行为
- pentaho - Pentaho 8.1 多租户
- maven - m2e 显示 jaxb2-maven-plugin schemagen 目标的执行错误
- selenium - 如何在运行时使用脚本模式在katalon中创建GlobalVariable?
- javascript - reCaptcha 回调:未启用功能以删除禁用属性
- javascript - JS JSON 流程
- regex - 正则表达式 - 匹配句子避免括号