How can I position a div relative to an image?

12,843

Solution 1

Somthing like this? http://jsfiddle.net/q0so8esf/

.imdesc {
    display: inline-block;
    vertical-align: middle;
    position: relative
}
.imdesc img {
    vertical-align: middle;
}
.imdesc p {
    text-align: center;
    background: #fc0;
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100px;
    height: 100px;
    margin: -50px;
    border-radius: 50px;
}

Solution 2

You could try this using absolute positioning for "foorbar":

<div class="container">
    <img class="image" src="http://lorempixel.com/400/400" />
    <div class="text">foobar</div>
</div>

.container {
    position: relative;
    display: inline-block;
}
.image {   }
.text {
    position: absolute;
    top: 50%;
    left: 50%;
    padding: 5px;
    margin-top: -14px;
    margin-left: -50px;
    width: 100px;
    background-color: white;
    text-align: center;
}

JSFIDDLE DEMO

You can adjust the width, and magins as needed to center or position the text exactly where you want it. The display: inline-block for the .container forces the div.container to not span the entire width of the page and allow us to center horizontally with absolute positioning.

Share:
12,843

Related videos on Youtube

gabyk00
Author by

gabyk00

Updated on September 15, 2022

Comments

  • gabyk00
    gabyk00 over 1 year

    I have a an image that may change its position depending on certain actions and several divs that I want to position on the img tag.

    The simplified code is as follows:

    <div>
        <img src="someRandomImageUrl">
        <div>foobar</div>
    </div>
    

    To better understand imagine I have an image with a small square somewhere around the center and I want the foobar message to be placed in the image square no matter where I position the image. Any ideas?

    • Salman A
      Salman A over 9 years
      Image cannot contain a div; put both items in a div and position that div instead.
  • morgler
    morgler over 6 years
    Wouldn't this center the div relative to the .container instead of relative to the .image? What if you add more elements to the container later on?