The width and height of the parent box is known, and the width and height of the child img is unknown. You want the img to cover the parent box and the image cannot be deformed.

the width and height of the parent box is known, and the width and height of the child img is unknown. You want the img to be covered with the parent box and the image cannot be deformed.

Jun.28,2022

css method
object-fit:cover;

js method


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <style>
            .div{width:400px;height: 400px;border:1px solid -sharpddd; overflow: hidden;}
            img{width: 100%;}
        </style>
    </head>
    <body>
        <div class="div" id="div">
            <img src="img/test.jpg" id="ele" />
        </div>
    </body>
    <script>
        var ele = document.getElementById("ele");
        var div = document.getElementById("div");
        ele.onload = function(){
            if(ele.naturalHeight < div.offsetHeight){
                ele.style.width = "auto";
                ele.style.height = "100%";
            }
        }
          
    </script>
</html>

img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b2c0b0-2badb.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b2c0b0-2badb.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?