How to make child div visible when resizing browser window?

If I have two nested div elements in my index.html page:

 <body> <div id="parent"> <div id="child"></div> </div> </body> 

parent div has a width of 900, a height of 800

I would like the child div be in the upper right corner of the parent div , so I define CSS for the child div as follows:

 #child { position: absolute; top: 0; right: 0; width: 300px; height: 30px; } 

The CSS is in order that it makes the child div located in the upper right corner of the parent div .

But , if I changed (reduced) the size of the browser window, at some point the child div will disappear (hide).

How to make a child div always visible, but still located in the upper right corner of the parent div no matter how the browser window is resized?

+4
source share
2 answers

Give the parental relative position so that the child position refers to it.

 #parent { position: relative; width: 900px; height: 800px; } #child { position: absolute; top: 0; right: 0; width: 300px; height: 30px; } 

EDIT: I misunderstood what you requested, and now that I have read it, I see that you want the child div to remain visible on the page no matter what, not only in the upper left corner of the parent. To do this, you need to bind the window to resize the event and change the position of the child div when the window width is less than the width of the parent. Change the correct position to the difference.

ok, here is a jquery that will do what I think you are asking for it:

 $(function(){ $(window).resize(function(){ var delta = parseInt($('#parent').width(), 10) - parseInt($(window).width(), 10); if (delta > 0) { $('#child').css('right', delta); } }); }); 

Two things:

  • If you quickly resize the window, the child div does not always return to the far right corner. I'm not sure if it is a matter of time before the width of the resulting window after it really has moved further or something else, but it works much better with slow resizing, which makes me believe that the best way to do this.
  • this does not handle moving the child div if the window was open, so it was too small to see the child div at first. This can be easily fixed using the same technique to find the best position for the child div, but only when the page loads, not when it changes.
+2
source

Depending on how you want the parent size to be a size, you could do one of the following things:

  • Set the size to #parent with maximum width instead of width

     #parent { position: absolute; max-width: 300px; height: 100%; } 
  • Size # transparent width with percent

     #parent { position: absolute; width: 100%; height: 100%; } 
  • Or just the size of #parent using something like this:

     #parent { position: absolute; top: 0px; bottom: 0px; left: 0px; right: 0px; } 

Using 2 or 3 does almost the same thing in this case, but 2 gives you more flexibility if you need extra space around #parent.

0
source

All Articles