"How can I display an image in HTML and dynamically adjust its size relative to the screen?"

Alex1347

New member
Joined
Feb 4, 2025
Messages
1
Programming Experience
1-3
I work with ASP.NET MVC project. How can I show image in html markup and dynamic set size relative size of monitor ? I show image on web-page, but I have case when image size more then monitor size and I need use scroll so see image. I can fix trouble with width, in my case I use JS script, but I don't fix the same trouble with height, I tried use: different JS scripts, set html and body tags height like 100%, set some styles for <img/> tag nad parent <div/> tag. But all cases don't work for me. In last case with css styles I can decrease size of image, but web-page size don't decrease and this incorrect size saved.

Image tag markup:

HTML:
<div class="row">
<div id="sc-area" class="col-md-10 offset-md-1 col-lg-8 offset-lg-2">
    <div class="wrapper text-center">
        <img id="image" class="screen-shot" />
    </div>
</div>
</div>



Different tries for fixing:

script1:

JavaScript:
<script>
var imgElement = document.getElementById("image");
   imgElement.onload = function () {
        var img = this;
        var imgBounds = {
            height: img.clientHeight,
            width: img.clientWidth
        };
        var scrAreaWidth = document.getElementById("sc-area").clientWidth;
        var scrAreaHeight = document.getElementById("sc-area").clientHeight;
        if (imgBounds.width >= scrAreaWidth)
        {
            img.style.width = "100%";
        }
        if (imgBounds.height >= scrAreaHeight)
        {
            img.style.height = "100%";
        }
    };
</script>

script2:

JavaScript:
<script>
    var imgElement = document.getElementById("image");
    var scrArea = document.getElementById("sc-area");
    imgElement.onload = function () {
    var scrAreaWidth = scrArea.clientWidth;
    var scrAreaHeight = scrArea.clientHeight;
    var imgWidth = imgElement.naturalWidth;
    var imgHeight = imgElement.naturalHeight;
    var widthRatio = scrAreaWidth / imgWidth;
    var heightRatio = scrAreaHeight / imgHeight;
    var scaleFactor = Math.min(widthRatio, heightRatio);
    imgElement.style.width = imgWidth * scaleFactor + "px";
    imgElement.style.height = imgHeight * scaleFactor + "px"; 
</script>

Styles:

CSS:
.container {
overflow: hidden;
height: 90%;
}

.container img {
object-fit: cover;
max-height: 90%;
}
 
Last edited:
I'm failing to find how this is a C# question. Looks more like a HTML/CSS/JavaScript question, but oh well.
 
Back
Top Bottom