0

I have an example of absolute positioned div which is centered in the page:

HTML

<div id="test1"><img src="http://www.interactivepixel.net/images/i01.jpg" width="500" height="333"/></div>

CSS

#test1{
   position:absolute;
   top:50%;    
   left:50%;
   width:500px;
   height:333px;
   margin-top:-166px;
   margin-left:-250px;
}

http://jsfiddle.net/ktFuN/

This works well until I shrink browser window so much that I get scrollbars and then even with the use of scrollbar I am loosing left and top side of the image, I cannot scroll all the way left and top of the image, like the centering doesn't work any more.

Why is that?

James A Mohler
  • 11,060
  • 15
  • 46
  • 72
Toniq
  • 4,492
  • 12
  • 50
  • 109

1 Answers1

0

when you reduce your window size, only the body size gets reduced, not that of the image or the explicitly sized div#test1. lets say the body size becomes 450x300 (width x height), ie less than the div size 500 x 333.

Apply the CSS top and left rules to the div

left of your div calculates to (50% of 450) = 225 top of your div calculates to (50% of 300) = 150

So your div now starts from point (225, 150) ie (left, top)

Now apply CSS negative margins to your div ie -250 to left and -166 to top

ie you div's position now becomes (225-250, 150-166) ie (-25, -16) absolute position.

Which means whenever you reduce you window size to be lesser than your absolutely positioned div size, some parts of your div would not be viewable, since body starts at (0, 0)

And since you've given that div negative margin for top and left, read this to understand how the div went out of view: http://coding.smashingmagazine.com/2009/07/27/the-definitive-guide-to-using-negative-margins/

You could check this thread for some generic css based solutions for centering an element.

Community
  • 1
  • 1
Sreenath S
  • 1,269
  • 1
  • 14
  • 21
  • Thanks, makes sense. So in order to achieve what I want I would need to use jquery and write something like this? http://jsfiddle.net/ktFuN/5/ Is there a way to write this just using css (no javascript or jquery)? – Toniq Aug 26 '12 at 12:41
  • are you looking for a generic solution to center any image to the center of a page ? or is it just this page, with div dimensions 500 x 333 ? – Sreenath S Aug 26 '12 at 13:04
  • Yes, for some kind of 'generic' element (not necessarily image) to be always centered, even in the window is resized. – Toniq Aug 28 '12 at 08:17
  • i didn't like the negative margin, in the first place. so i used a solution from here: http://stackoverflow.com/questions/953918/how-to-align-a-div-to-the-middle-of-the-page. don't know if this would serve your purpose. i've taken out the `position:absolute` as well. chk it out http://jsfiddle.net/ktFuN/6/. – Sreenath S Aug 28 '12 at 11:52