Fixed size label wrapped with img, vertically centered picture when img is not fixed size

There is a need to load an img tag with an indeterminate size in a container, but this picture needs to be vertically centered. Because the size of the picture cannot be pre-determined, it is impossible to use the methods commonly used in css to achieve the effect of vertically centered. One can think of is to dynamically obtain the size of the picture through js, and then according to the size of the pictureSmall to rearrange its style to achieve a vertical centering effect.

The code and detailed instructions are attached below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Picture Vertical and Horizontal Centering</title>
    <style>
        .img-box{
            margin: 20px auto;
            position: relative;
            width: 100px;
            height: 100px;
            border: 1px solid #e3e3e3;
            overflow: hidden;
        }

        .img-box img{
            position: absolute;
            top: 50%;
            left: 50%;
        }
    </style>
</head>
<body>
    <ul>
        <li class="img-box">
            <img src="app-11.png" alt="">
        </li>
        <li class="img-box">
            <img src="img/home.png" alt="">
        </li>
        <li class="img-box">
            <img src="03.jpg" alt="">
        </li>
    </ul>

    <script>
        window.onload = function(){
            var img = document.querySelectorAll(".img-box img");
            var imgSrc = [];//Path to save all pictures
            var imgValue = [];//Save width and height values for all pictures
            for(var i=0;i<img.length;i++){
                imgSrc[i] = img[i].src;
                imgValue[i] = getImageWidth(imgSrc[i],function(w,h){
                    //console.log({width:w,height:h});
                });
                img[i].style.marginLeft = -imgValue[i].width/2+'px';//Adjust its position to the left
                img[i].style.marginTop = -imgValue[i].height/2+'px';//Adjust its position from the top
            }

        }
        /**
         * [getImageWidth Get the width and height of the picture]
         * @param  {[type]}   url      [Picture Path]
         * @param  {Function} callback [Width and Height Parameter Callback]
         * @return {[type]}            [Return Object]
         */
        function getImageWidth(url,callback){
            var img = new Image();
            img.src = url;
            // If the picture is cached, return the cached data directly
            if(img.complete){
                callback(img.width, img.height);
                return {"width":img.width,"height":img.height};//Return width and height values
            }else{
                // Events Completed Loading
                img.onload = function(){
                    callback(img.width, img.height);
                    return {"width":img.width,"height":img.height};//Return width and height values
                }
            }
        }

    </script>
</body>
</html>

The key code is the size of the picture obtained by the Image() object. If the size cannot be obtained, subsequent operations will not be possible because the common js method of getting the size by style is unsuccessful without setting the size of the picture.

In the code, the size value of each picture is saved as a numeric object and returned, so that the number of multiple pictures can be received externally through an array, which facilitates the operation of multiple pictures; once the size of the picture is obtained, it can be easily set in the vertical center of the picture by using the traditional way of resetting the style.

This operation is for special cases, that is, when the picture is not very different from the outside container, the effect is better. If the picture is too large, then vertical centering is meaningless, because only a small part of the information in the picture can be seen, there is no difference with not setting its center, it is best to limit the size of the picture, do not exceed the outside contentThe machine is too big, otherwise it would not make much sense to do so.

The following is an illustration of the implementation of the code:

Posted on Sun, 17 May 2020 12:33:43 -0400 by lotrfan