yariv bar yariv bar - 10 months ago 43
Javascript Question

append div after img and vertically align it

I am trying to append a

using jQuery after an image and than place it in the middle of the image. so if this is the image

<div class="entry">
<img class="alignnone size-full wp-image-7711" src="http://some-source.com/img" alt="celebrity-girlfriends-6" width="728" height="382">

i append the div like this:

jQuery('.entry').find('img:first').after('<div id="test"></div>');

but is there a way to place the new div in the middle of the image?


You can use position: absolute on #test and position: relative on parent div

$('.entry').find('img:first').after('<div id="test">Test</div>');
.entry {
  position: relative;
  display: inline-block;
#test {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 30px;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="entry">
  <img src="http://placehold.it/350x150">