Home > Back-end >  How to get nested flexbox to work with image
How to get nested flexbox to work with image

Time:03-02

So my use case is pretty simple. I have an image and a div with text inside.

The div has flex set to the column.

I want to get flex set to row for the text image so that they are side by side.

While the text flexbox is congruent, currently the image displays above the text. What is wrong with my code here?

.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 >
  <div >
    <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>

enter image description here

CodePudding user response:

you need to set the z-index property (https://idg.net.ua/blog/uchebnik-css/razmetka-css/z-index)

CodePudding user response:

Assuming you are using some sort of React framework, I changed className to class.

So the problem is actually because of the absolute positioning (has nothing to do with z-index). Absolute positioning with position values set will have no regard for flex, as the browser is instructing them to retain this position absolutely.

Now it seems you have the absolute positioning because you want the elements in prompt to be centered on the page vertically and horizontally. There are ways to do this using transform, but there is an easier way using the body element. Just simply add min-height: 100vh; with display: flex;, then instruct the browser to position it in the center with justify-content: center; ~ center of the page.

Moving on to the flex, now that your absolute positioning is gone and you remove the fixed height and width on prompt you can use align-items: center; to position them inline, or whatever align you desire. Then I just used gap to space them out.

Feel free to adjust as necessary. See the snippet below or try out the 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 >
    <a href="https://www.google.com">
      <img src="https://dummyimage.com/100x100/000/fff" alt="Refresh Button for Prompt" />
    </a>
    <div >
      <h1>Sketch</h1>
      <h2>90% Dog</h2>
      <h2>10% Human</h2>
    </div>
  </div>
</body>

  • Related