Vertically centering an element inside an image

Viewed 52

I know there are many ways to vertically center a div inside another div, but what I'm experiencing problems on is a way to vertically center a div inside an image element.

Here's the minimum code I require:

HTML:

<img class="star" src="star.png"></img>

<div class="vCenter">Text to be vertically centered in the image.</div>

CSS:

.star {
    position: absolute; /* I need this value for another thing in my project */
}

Also, the height of the image is in percentage.

4 Answers
  1. Wrap the image in another element
  2. Move the position: absolute to the wrapper element
  3. Center the text in the wrapper element, let the image expand the wrapper element

.wrapper {
  position: absolute;
  top: 30px;
  left: 10px;
  
  display: flex;
  justify-contents: center;
  align-items: center;
}

.wrapper img {
  /* debug */
  background: yellow;
  width: 300px;
  height: 300px;
}

.wrapper .vCenter {
  position: absolute;
  left:50%;
  max-width: 100%;
  transform: translateX(-50%);
}
<div class="wrapper">
  <img class="star" src="star.png" />

  <div class="vCenter">Text to be vertically centered in the image.</div>
</div>

Try this way:


    <div class="container">
       <img class="star" src="star.png"></img>
       <div class="centered-div">Text to be vertically centered in the image.</div>
    </div>


    .container {
       position: relative;
    }
    
    .star {
       display: block;
       margin: auto;
       width: 100%;
    }
    
    .centered-div {
       position: absolute;
       left: 50%;
       top: 50%;
       transform: translate(-50%, -50%);
    }

You may add your image and text to a container set to position:absolute

This should do the job ;-)

.container {
  position: absolute;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  // just add the desired position to this container
}

.star {
  position: absolute;
}
.vCenter {
  z-index: 1;
}
<div class="container">
      <img class="star" src="star.png" />
      <div class="vCenter">Text to be vertically centered in the image.</div>
</div>

Related