Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I put a div over an image?

Tags:

html

css

I am trying to put a div over an image so that it acts like a caption, directly ontop of the image.

Sometimes the caption is longer than other times so I can't set a specific margin-top:-px because sometimes the height of the caption is longer.

I tried this and the background of the link (black) does not show, also like I just stated, the caption height changes so this method is garbage:

 <div>  

  <img src = "<? echo $image_url ?>" style="float:left;min-width:220px;max-width:220px;">
   <a href="LINK" ><div style="width:210px;background-color:black;color:white;bottom:0;margin-top:-20px;padding-left:10px;padding-top:10px;font-size:16px;"><? echo $title ?></div></a>

 </div>
like image 855
Thingamajig Avatar asked Oct 01 '12 19:10

Thingamajig


2 Answers

Try something like this:

<div style="position:relative;">  

  <img src = "<? echo $image_url ?>" style="min-width:220px;max-width:220px;">
   <div style="position:absolute;width:210px;background-color:black;color:white;top:0;left:0;padding-left:10px;padding-top:10px;font-size:16px;z-index:5;"><a href="LINK" ><? echo $title ?></a></div>

</div>

You had a few things going on:
1) You had a div inside an 'a' tag. You shouldn't put block level elements (like divs) inside inline level elements (like a's).
2) Remove the float from the image, set your outer div's position to relative and your inner div's position to absolute, then absolutely position it to the top of the containing div. From there, add a z-index greater than 0 to the inner div for good measure, to ensure it stays stacked above the image.

like image 88
Mike Avatar answered Sep 18 '22 14:09

Mike


Add position:absolute; left:0px;top:0px;z-index: 2; to current div, and add style="position:relative;" in the parent div

<div style="position:relative;">  

  <img src = "<? echo $image_url ?>" style="float:left;min-width:220px;max-width:220px;">

<a href="LINK" ><div style="position:absolute;z-index: 2;left:0px;top:0px;width:210px;background-color:black;color:white;bottom:0;padding-left:10px;padding-top:10px;font-size:16px;"><? echo $title ?></div></a>

like image 29
Krishna Kumar Avatar answered Sep 21 '22 14:09

Krishna Kumar