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

前端 未结 12 1045
庸人自扰
庸人自扰 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:10

    If you dont know the image sizes but you have uploaded the pictures next to the size of the container (maybe bigger or smaller images), this post can be useful. Something that is working for me is the next code:

    
        
    
    
        
    
    
        
    
    

    And in the .css file you have the next rules:

    a.linkPic{
        position:relative;
        display: block;
        width: 200px; height:180px; overflow:hidden;
    }
    a.linkPic img{
        position:absolute;
    }
    

    You can notice you have an image tag inside the a.linkPic, so first you have to set it as "position:relative" for containing the "img" absolute element. The trick to center the picture without problems is a little jQuery code. Follow the comments to understand what is going on (some lines were taken from the Vladimir Maryasov post in this page):

    $("a.linkPic img").each(function() {
        // Get container size
        var wrapW = $("a.linkPic").width();
        var wrapH = $("a.linkPic").height();
    
        // Get image sizes
        var imgW = $(this).width();
        var imgH = $(this).height();
    
        // Compare if image is bigger than container
        // If image is bigger, we have to adjust positions
        // and if dont, we have to center it inside the container
        if (imgW > wrapW && imgH > wrapH) 
        {
            // Centrar por medio de cálculos
            var moveX = (imgW - wrapW)/2;
            var moveY = (imgH - wrapH)/2;
    
            // attach negative and pixel for CSS rule
            var hWide = '-' + moveX + 'px';
            var hTall = '-' + moveY + 'px';
    
            $(this).addClass("imgCenterInDiv").css({
                "margin-left" : hWide,
                "margin-top" : hTall
            });
        } else {
            $(this).addClass("imgCenterInDiv").css({
                "left" : 0,
                "right" : 0,
                "top" : 0,
                "bottom" : 0,
                "margin" : "auto",
            });
        }//if
    });
    

    After this, all the pictures inside in a.linkPic containers will be placed perfectly centered. I Hope this post can be useful for someone!

提交回复
热议问题