title: How to auto adjust margin to Auto center vertical & horizontal using jQuery and CSS margin
body: <p>I'm trying to center a block element (img or div) to a container which has a % width and height %. </p>
  
  <p>Here's what I did. <a href="http://jsbin.com/ibakuw" rel="nofollow">http://jsbin.com/ibakuw</a></p>
  
  <pre><code> $('#container img')
      .css({
        'margin': ($('#container').height() - $('#container img').height()) / 2 + 'auto', 
        'background':'red'});
  </code></pre>
  
  <p>I don't want to use this  <code>{position:absolute; top:50%; height:240px; margin-top:-120px; }</code>
  approach to center vertically because the elements overflows my browser or container. I just need it to be constraint within the browser. </p>
  
  <p>Please help. thank You!</p>
  
  <p><strong>edited:</strong></p>
  
  <p>I added   <code>$(window).resize(function() {</code> here <a href="http://jsbin.com/ibakuw/5" rel="nofollow">http://jsbin.com/ibakuw/5</a></p>
  
  <pre><code>var contHeight = $('body').height(),
      paddVertical = ($('#container').height() - $('#container img').height()) / 2,
      paddHorizon =  ($('#container').width() - $('#container img').width()) / 2;
  
  $(function() {
  
    $('#container img')
      .css({
        'marginLeft' : paddHorizon +'px',
        'marginTop' : paddVertical +'px'  
      });
  
  
    $(window).resize(function() {
      $('#container img')
        .css({
          'marginLeft' : paddHorizon +'px',
          'marginTop' : paddVertical +'px'  
        });
    });  
  
  });
  </code></pre>