Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlay a sibling box while respecting parent box

I'm thinking this isn't possible, but I'm not a CSS expert, so I thought I'd check. I've got a translucent div absolutely positioned over an image. That's good so far, but I'd like to force my translucent div to respect the box in which it and the image are contained.

<div class="parent">
  <div class="title-bar"> /* prolly not important */
    <h2>Title</h2>
  </div>
  <img src="whatever"/>
  <div class="overlay">
    A few lines of txt
  </div>
</div>

The more I think about it, the more I think I may be asking for too much - I want the parent to expand with the img, but the overlay to be constrained by the parent. Can this be done?

like image 361
user1269310 Avatar asked Sep 25 '12 15:09

user1269310


2 Answers

To force the container expand with the child img, make it float.
To force the overlay relate to container position and size, make the container relative.

.parent {
    float: left;
    position: relative;
}

To force the overlay respect the bounds of the container, use percents.

.overlay {
    position: absolute;
    max-width: 100%;
    /* And then, position it at will */
    top: 0;
    left: 0;
}

I've prepared an example: http://jsfiddle.net/rYnVL/

like image 91
albertedevigo Avatar answered Nov 05 '22 12:11

albertedevigo


It's doable, but not quite beautiful :

<div id="parent">
    <div id="abs">stuff fadsfasd fsad fasdsdaf </div>
    <img src="/img/logo.png" />
</div>

#parent {width:auto; height:auto; border:1px solid blue; background-color:grey;position:relative; display:block;float:left;}

#abs {position:absolute;width:100%;height:100%;background:#ff0000;opacity:0.4;}

Main point to note :
parent floats to not have a 100% width. Position is relative.
abs is absolute, with 100% size.

also, if abs content is bigger than the image, it will overflow. If you do not like this, just add overflow:hidden.

like image 42
Kraz Avatar answered Nov 05 '22 11:11

Kraz