Vertically and Horizontally Center Image inside a Div, if you don't know Image's Size?

前端 未结 12 1090
庸人自扰
庸人自扰 2020-12-29 10:28

If I have a fixed sized container div, and an unknown sized image, how do I horizontally and vertically center it?

  • using pure css
  • using JQuery if css
12条回答
  •  自闭症患者
    2020-12-29 11:09

    If setting the image as a background image and centering it that way isn't an option, the jQuery to adapt the answer you linked for static images would go:

    $(".fixed-div img.variable").each(function(){
      //get height and width (unitless) and divide by 2
      var hWide = ($(this).width())/2; //half the image's width
      var hTall = ($(this).height())/2; //half the image's height, etc.
    
      // attach negative and pixel for CSS rule
      hWide = '-' + hWide + 'px';
      hTall = '-' + hTall + 'px';
    
      $(this).addClass("js-fix").css({
        "margin-left" : hWide,
        "margin-top" : hTall
      });
    });
    

    assuming a CSS class defined as

    .variable.js-fix {
      position:absolute;
      top:50%;
      left:50%;
    }
    

    with the fixed-width div having a height and position:relative declared.

    [important js edit: switched '.style()' to '.css()']

提交回复
热议问题