当容器变成弹性容器 gatsby 时,图像消失

mmm*_*mmm 11 flexbox gatsby

我有一个用 Gatsby 版本 2 制作的页面,我想在 flexbox 容器内从 gatsby-image 制作组件。当我删除display: flex;属性时图像出现,当容器是 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
        }
      }
    }
  }
`
Run Code Online (Sandbox Code Playgroud)

N. *_*nez 13

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

您正在使用 GatsbyImageSharpFluid。与“固定”相反的盖茨比形象的“流动”类型。您已经设置了最大宽度是。但最终,“流动”的想法是图像将采用其容器的大小。Max-width 是它可以扩展到的最大值 - 只有当容器达到该宽度时才达到。

在 flexbox 中,它是设置容器宽度的内容宽度。这是 flex 的原理...但是流体图像没有宽度,因此您的 flex 容器也没有宽度 => 您的图像不会出现。

解决方案:为您的 flex-item 设置固定宽度或使用固定的 Gatsby Image 代替。

请参阅 Gatsby 文档关于固定图像与流体图像:https : //www.gatsbyjs.org/docs/gatsby-image/


mmm*_*mmm 9

我的朋友建议我添加

& > * {
  flex-grow: 1;
}
Run Code Online (Sandbox Code Playgroud)

这将 flex-grow 应用于 flex 容器的直接子级。

我不明白为什么图像会消失,但它可能与 Gatsby 添加的包装元素有关。

我想拥有 flexbox 的通常行为,我相信如果空间允许,图像和文本 div 会在同一行上,但我不得不添加 max-width 和 min-width 以获得我想要的行为.