如何让嵌套的 flexbox 与图像一起工作

How to get nested flexbox to work with image

所以我的用例非常简单。我有一张图片和一张 div 里面有文字。

div 已将 flex 设置为列。

我想将 flex 设置为文本 + 图像的行,以便它们并排。

虽然文本 flexbox 是一致的,但当前图像显示在文本上方。我这里的代码有什么问题?

.promptParent {
  display: flex;
  flex-direction: row;
}

.prompt {
  position: absolute;
  width: 540px;
  height: 180px;
  left: 450px;
  top: 67px;
  font-family: Coiny;
  font-style: normal;
  font-weight: normal;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

h1 {
  font-size: 72px;
}

h2 {
  font-size: 36px;
  margin-bottom: 0;
  margin-top: 0;
}
<div class="promptParent">
  <div class="prompt">
    <h1>Sketch</h1>
    <h2>90% Dog</h2>
    <h2>10% Human</h2>
  </div>
  <a href="https://www.google.com">
    <img src="/" alt="Refresh Button for Prompt" />
  </a>
</div>

您需要设置 z-index 属性 (https://idg.net.ua/blog/uchebnik-css/razmetka-css/z-index)

假设您正在使用某种 React 框架,我将 className 更改为 class

所以问题实际上是因为绝对定位(与z-index无关)。设置了位置值的绝对定位将不考虑 flex,因为浏览器指示它们绝对保留此位置。

现在您似乎有了绝对定位,因为您希望 prompt 中的元素在页面的垂直和水平方向上居中。有多种方法可以使用 transform 来执行此操作,但使用 body 元素有一种更简单的方法。只需简单地添加 min-height: 100vh;display: flex;,然后指示浏览器将其定位在 justify-content: center; ~ 页面中心。

继续使用 flex,现在您的绝对定位已经消失并且您删除了 prompt 上的固定高度和宽度,您可以使用 align-items: center; 将它们定位为内联,或任何您想要的对齐方式.然后我就用 gap 把它们 space 出来了。

如有必要,请随时进行调整。请参阅下面的代码片段或尝试 Fiddle.

body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.promptParent {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 3em;
}

.prompt {
  font-family: Coiny;
  font-style: normal;
  font-weight: normal;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

h1 {
  font-size: 72px;
}

h2 {
  font-size: 36px;
  margin-bottom: 0;
  margin-top: 0;
}
<body>
  <div class="promptParent">
    <a href="https://www.google.com">
      <img src="https://dummyimage.com/100x100/000/fff" alt="Refresh Button for Prompt" />
    </a>
    <div class="prompt">
      <h1>Sketch</h1>
      <h2>90% Dog</h2>
      <h2>10% Human</h2>
    </div>
  </div>
</body>