title: Using JQuery to Dynamically Align Images Center
body: <p>I'm trying to dynamically align images center within a grid type format. Each image is dynamically loaded from a CDN with a max-height and max-width for <code>.thumbnail img</code>. The container div is fixed width and height. </p>
  
  <pre><code>#storeItems .thumbnail {
  border:1px solid #637678;
  width:136px;
  height:151px;
  padding:1px;
  position:relative;
  margin:0 auto;
  display:block;
  overflow:hidden;
  }
  #storeItems .thumbnail img {
  max-width:130px;
  max-height:130px;
  display:block;
  position:relative;
  }
  </code></pre>
  
  <p>The JavaScript I created does align images correctly within IE8+, Chrome, Opera, Safari, and Firefox. However, my issue problem arises in IE8+, Opera, and Firefox when you first load the page it will not align until you refresh the page. Once the page is cached it keeps the alignment fine. This only seems to after on initial page load with no cached pages.</p>
  
  <pre><code>(function($) {
  $("#storeItems .thumbnail").each(function(i){
      var img = $(this).find('img');
  
      var y = $(this).height(),
          x = $(this).width();
      /**
       * WebKit browsers which incorrectly calculates margin
       */
      if($.browser.webkit) {
          $(this).css({
              'display': 'table-cell',
              'vertical-align': 'middle',
              'text-align': 'center'
          });
          img.css({
              'margin': 'auto auto'
          });
      }
      else {
          img.css({
              'margin-top': ((y-img.height())/2)+'px',
              'margin-left': ((x-img.width())/2)+'px'
          });
      }
  });
  })(jQuery);
  </code></pre>
  
  <p>I have the JavaScript loading at the bottom of the page. I tried loading it in the header. I also used <code>$(document).ready();</code> in both the header and at the bottom; it did not align at all after trying that. Is there something I'm missing? Seems like calculation does not happen in these browsers on the first run. Any thoughts?</p>