How can I position a div relative to an image?
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;
}
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.
Related videos on Youtube
gabyk00
Updated on September 15, 2022Comments
-
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 theimg
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 over 9 yearsImage cannot contain a div; put both items in a div and position that div instead.
-
-
morgler over 6 yearsWouldn'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?