简体   繁体   中英

Fixed size for image in HTML and CSS

I have add an image on the top of my webpage. My css and HTML code is given below:

<style>
.logo {
    display: inline-block;
    vertical-align:top;
    width: 600px;
    height: 100px;
    margin-right: 50px;
    margin-top: 50px;    
}
</style>
<nav class="navigation-bar">
    <img class="logo" src="D:\Users\703191994\Desktop\Ima\333.jpg">

Now while zoom in and zoom out the web page image looks smaller and bigger and not fixed sized. While scrolling mouse size is not fixed for image.

How to resolve this issue?

it is the normal behavior of the browser. when you zoom in the image looks bigger. but if you right click and choose "inspect" option you see that the width of image is not changed: 在此处输入图片说明

you can do something like this to keep image size fixed

 <div class="item">
    <img src="yourImage">
 </div>


img {
    width: 100%;
    height: 100%;
}

.item {
    float: left;
    margin: 3px;
    padding: 3px;
    border: 1px dashed #000;
    width: 500px;
    height: 500px;
}

if your goal is to have an image that "looks" the same size when the browser is zoomed in or out, and actually width and height are changing. I added some jquery code and changed your css like the codes below:

 // java.js file let primaryWidth = 600; // primary width of image let primaryWindow = 1280; // primary width of window let aspect = primaryWidth / primaryWindow; let imgElem = $(".logo"); $(window).resize(function() { /* this function is called when the window is resizes */ console.log($(window).innerWidth()); let winWidth = $(window).innerWidth(); let newWidth = winWidth * aspect; imgElem.css("width", newWidth + "px"); })
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .logo { display: inline-block; vertical-align:top; width: 600px; } .navigation-bar { position: absolute; top: 10%; left: 2%; } </style> </head> <body> <nav class="navigation-bar"> <img class="logo" src="02.jpg"> </nav> <script src="jquery-3.5.1.js"></script> <script src="java.js"></script> </body> </html>

I think it is necessary to mention that at first you must set your zoom level of browser to 100%. and also the values of "primaryWidth" and "primaryWindow" variables could change according to your image and your computer window width.

I also deleted the "height" property in styles. because it is set automatically.

        .logo {
        display: inline-block;
        vertical-align:top;
        width: 60vw;
        height: 10vh;
        margin-right: 50px;
        margin-top: 50px;    
        }

use vw(viewport width) and vh(viewport height) instead of px

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM