user887515
user887515

Reputation: 804

CSS - parent div is not expanding to width/height of child

I am looking to overlay a caption on to an image. I have managed to do this, but the image is expanding out of the parent div.

I have the containing div set to inline-block, as I want it to 'auto size', not take up width: 100%. If you look at the current output, you'll see the image could be within the black bordered box.

It only needs to work in Chrome, if you encounter cross-browser issues.

Thanks in advance!

LIVE DEMO


CSS:

#body_content {
    border: solid 1px blue;
    display: inline-block;    
    padding: 5px;
}
#body_header {
    border: solid 1px red;
    font-size: 25px;
    padding: 5px;
}
#body_image {
    position: absolute;
}
#body_image_caption {
    color: white;
    line-height: 30px;
    margin-left: 10px;
}
#body_image_container {
    background: white;
    border: solid 1px black;
    margin-top: 3px;
    padding: 10px;
}
#body_image_overlay {
    background-color: black;
    bottom: 5px;
    display: block;
    height: 30px;
    opacity: 0.85;
    position: absolute;
    width: 100%;    
}​

HTML:

<div id="body_content">
   <div id="body_header">
      Heading
   </div>
   <div id="body_image_container">
      <div id="body_image">
          <img src="http://i.imgur.com/s6G8n.jpg" width="200" height="200" />
          <div id="body_image_overlay">
             <div id="body_image_caption">
                Some Text
             </div>
          </div>
      </div>
   </div>
</div>

Upvotes: 8

Views: 41238

Answers (3)

Sumit Gera
Sumit Gera

Reputation: 1241

Check this fiddle. You need to set the position of the child element of the image to be absolute and the parent element to be relative. Change the width of the caption accordingly.

child-element {
    position:absolute;
}

parent-element {
    position:relative
}

http://jsfiddle.net/AaXTm/4/

Upvotes: 2

cimmanon
cimmanon

Reputation: 68319

The #body_image element is escaping from the #body_image_container because its position is set to absolute. Absolutely positioned elements are removed from the document's flow, causing parent elements to collapse as though the child element wasn't there. If you change it to relative, then it becomes contained within the black box:

#body_image{
    position: relative;
}

http://jsfiddle.net/AaXTm/2/

Upvotes: 20

Nalan Madheswaran
Nalan Madheswaran

Reputation: 10562

Try this css in parent div.

Overflow:auto

Upvotes: 8

Related Questions