0

Trying to center a div inside an image with flexbox (I only want flexbox), but since img does not have closing tag, I cannot make it work. How to do?

.uno {
   display: flex;
   justify-content: center;
   align-items: center;
}
<div class="uno">
   <img src="https://www.placecage.com/300/300" alt="">
   <h1>Center this text</h1>
</div>

This puts my text in the center but to the right of the img. Only flexbox solutions.

VXp
  • 11,598
  • 6
  • 31
  • 46
Rju
  • 63
  • 1
  • 10

2 Answers2

2

To place the text over the image , give absolute position to h1 element and add position relative on the container element.

Since you have set justify-content and align-items properties on the flex container to center, when text is placed over the image, it will be centered horizontally and vertically.

.uno {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

h1 {
  position: absolute;
}
<div class="uno">
  <img src="https://www.placecage.com/300/300" alt="" />
  <h1>
    Center this text
  </h1>
</div>
Yousaf
  • 27,861
  • 6
  • 44
  • 69
0

You can't place other elements inside an img tag. As others have said, it would make more sense to use a background-image but I'm guessing there's a reason you need it like this.

For how you want it you'd have to set the image to position: absolute; z-index: 0; and the h1 to z-index: 1;, also, the height of .uno would need to be reset otherwise it could clip off the edges of the page.

body {
  height: 100vh;
  width: 100%;
}

.uno {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

img {
  position: absolute;
  z-index: 0;
}

h1 {
  z-index: 1;
}
<div class="uno">
  <img src="https://www.placecage.com/300/300" alt="" />
  <h1>
    Center this text
  </h1>
</div>

Love the image btw.

Daniel_Knights
  • 7,940
  • 4
  • 21
  • 49