0

I've followed the code on this link : Using jQuery to center a DIV on the screen and my div isn't centered . Any ideas why ?

in my javascript error console there seems to be no error . Here is my code :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">     
<html xmlns="http://www.w3.org/1999/xhtml">
   <head runat="server">
     <title></title>
     <script src="./Scripts/jquery-1.4.1.js" type="text/javascript">
         (function ($) {
             $.fn.extend({
                 center: function () {
                     return this.each(function () {
                         var top = ($(window).height() -  $(this).outerHeight()) / 2;
                         var left = ($(window).width() -  $(this).outerWidth()) / 2;
                         $(this).css({ position: 'absolute', margin: 0, top: (top > 0 ? top : 0) + 'px', left: (left > 0 ? left : 0) + 'px' });
                     });
                 }
             });
         })(jQuery);

         $('#login').center();
     </script> 
     <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
 </head> 
 <body bgcolor="#0066cc">     
     <form id="form1" runat="server">
     <div>
     <h1>Welcome to SeeUBook</h1>         
     </div>
     <div id="login">     
         //some code
       </div>         
     </form>
  </body>
</html>
Community
  • 1
  • 1
Alex
  • 10,869
  • 28
  • 93
  • 165
  • It's a sad state of affairs when one needs to throw javascript at a simple CSS problem. – Rob Dec 26 '10 at 11:42

2 Answers2

3

You need to run the plugin on the element once it's in the DOM (on document.ready), like this:

$(function() {
  $('#login').center();
});

...currently it's running before there's a id="login" element to find in the page, so it's not centering anything.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • i've replaced the $('#login').center(); with $(function() {$('#login').center();}); and it still doesn't work :-? – Alex Dec 26 '10 at 11:10
  • @Badescu - It should be centered, keep in mind `
    ` elements expand to their full width by default, are you giving it a smaller one? See what I mean here: http://www.jsfiddle.net/nick_craver/dhDpF/
    – Nick Craver Dec 26 '10 at 11:13
0

You can just write in CSS:

#content {
     width: 9999px ;/*how wide you want it or you could set it to auto*/
     margin-left: auto ;
     margin-right: auto ;
   }
George
  • 1