andyuk andyuk - 1 year ago 72
Javascript Question

Overlaying one div over another, but not knowing the size of the div

I'm trying to lay one div over another. This is really simple if you know the dimensions of the div.

Solved here:
How to overlay one div over another div

So, here is my HTML:

<div class="container">
<div class="overlay"></div>
<div class="content"></div>

In my case, I don't know the exact dimensions of the "content" or "container" div. This is because I don't have control over any of the content in the div (we are making our app extensible for 3rd party developers).

See my example on jsFiddle
The overlay should cover the content entirely. Width 100% and Height 100%. However, this does not work because in my example I positioned the overlay absolutely.

One solution is to use JavaScript to get the size of the content div and then set the size of the overlay. I don't like this solution much since if image sizes are not specified, you need to wait until images are loaded and recalculate the size of the div.

Is there any way of solving this problem in CSS? 

Answer Source

It's not possible to do this because:

  1. The overlay is not contained by anything to restrict it's size (since there is no height/width applied to the container).
  2. The size of the content div can change as content loads (since it has no fixed width/height).

I solved this by using JavaScript*. Eg.

function resizeOverlay() {
    width: $('.content').width()
    height: $('.content').height()
$('.content').find('img').on('load', resizeOverlay);

*Code not tested.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download