Search code examples
jqueryalignment

Vertically Center - jQuery


I have a bunch of images at random heights and widths that need to be vertically and horizontally centered.

For whatever reason it stopped working. Could anyone spare some help? I have no knowledge of jQuery (someone gave me the code).

Image 1

Image 2

//jQuery by Juan Mendes
$(window).load(function(){
  var $img = $('img');

  $img.css({'display': 'block',
          'margin-left': '-' + ($img.width() / 2) + 'px',
          'margin-top': '-' + ($img.height() / 2) + 'px'});
});

Solution

  • I added a breakpoint in center.js and that shows that your images have no width/height when you're calling $img.css

    For you to guarantee that your script runs after images have been loaded, you have to wrap it with an onload handler

    $(window).load(function(){
      var $img = $('img');
    
      $img.css({'display': 'block',
              'margin-left': '-' + ($img.width() / 2) + 'px',
              'margin-top': '-' + ($img.height() / 2) + 'px'});
    });