当容器变成 flex container gatsby 时图像消失

image disappears when container becomes flex container gatsby

我有一个用 Gatsby 版本 2 制作的页面,我想在 flexbox 容器中从 gatsby-image 制作组件。当我删除 display: flex; 属性 时图像出现,当容器是弹性容器时图像消失。

当我在开发工具中查看 Gatsby 应用的 CSS 样式时,我尝试一个一个地取消选择属性。当我取消选择 position: absolute; 属性 时,图像出现了,但它的大小或位置不正确。

我也试过在容器上设置 flex-direction: column;,这使得两个图像中的第二个出现。但是,我更希望这个值是行。

在图片上设置overflow: visible !important;并没有显示图片。

import React from "react"
import { Link } from "gatsby"
import { css } from "@emotion/core"
import Img from "gatsby-image"

const testPage = props => (
  <div
    css={css`
      display: flex;
      flex-direction: // column or row;
    `}
  >
    <Img
      fluid={props.data.ImgOne.childImageSharp.fluid}
      alt="description"
      fadeIn={true}
      style={{
        ...(props.style || {}),
        maxWidth: "400px",
        // position: "absolute",
        // overflow: "visible !important",
        ...props.data.ImgOne.childImageSharp.fluid.presentationWidth,
        margin: "0 auto", // Used to center the image
      }}
    />
    Some text to go in between pics.
    <Img
      fluid={props.data.ImgTwo.childImageSharp.fluid}
      alt="description"
      fadeIn={true}
    />
  </div>
)

export default testPage

export const pageQuery = graphql`
  query {
    ImgOne: file(relativePath: { eq: "ImageOne.jpg" }) {
      childImageSharp {
        fluid(maxWidth: 400) {
          ...GatsbyImageSharpFluid_withWebp
          presentationWidth
        }
      }
    }

    ImgTwo: file(relativePath: { eq: "ImageTwo.jpg" }) {
      childImageSharp {
        fluid(maxWidth: 800) {
          ...GatsbyImageSharpFluid_withWebp
        }
      }
    }
  }
`

朋友建议我加

& > * {
  flex-grow: 1;
}

这适用于 flex-grow 弹性容器的直接子代。

我不明白图像消失的确切原因,但它可能与 Gatsby 添加的包装元素有关。

我想要 flexbox 的通常行为,我相信如果 space 允许的话,图像和文本 div 会在同一行,但我不得不乱加max-width 和 min-width 以获得我想要的行为。

我遇到了同样的问题。原来是因为对 Flexbox 和 Gatsby Image 的工作原理缺乏了解。

您正在使用 GatsbyImageSharpFluid。 "fluid" 类型的 Gatsby 图像与 "fixed" 相对。你已经设置了最大宽度是。但最终,"fluid" 的想法是图像将采用其容器的大小。最大宽度是它可以扩展到的最大值 - 只有当容器达到该宽度时才能达到。

在flexbox中,设置容器宽度的是内容宽度。这是flex的原理...但是流体图像没有宽度所以你的flex容器也没有宽度=>你的图像没有出现。

解决方案:为弹性项目设置固定宽度或改用固定的 Gatsby 图像。

请参阅 Gatsby 文档,了解固定图像与流动图像:https://www.gatsbyjs.org/docs/gatsby-image/