繁体   English   中英

HTML 和 CSS 中图像的固定大小

[英]Fixed size for image in HTML and CSS

我在我的网页顶部添加了一张图片。 我的 css 和 HTML 代码如下:

<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">

现在,在放大和缩小网页图像时,它看起来越来越小,而且大小不固定。 虽然滚动鼠标大小不是固定的图像。

如何解决这个问题?

这是浏览器的正常行为。 当你放大图像时看起来更大。 但是如果您右键单击并选择“检查”选项,您会看到图像的宽度没有改变: 在此处输入图片说明

你可以做这样的事情来保持图像大小固定

 <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;
}

如果您的目标是在浏览器放大或缩小时“看起来”相同大小的图像,并且实际上宽度和高度正在发生变化。 我添加了一些 jquery 代码并像下面的代码一样更改了你的 css:

 // 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>

我认为有必要提一下,首先您必须将浏览器的缩放级别设置为 100%。 并且“primaryWidth”和“primaryWindow”变量的值可能会根据您的图像和计算机窗口宽度而变化。

我还删除了样式中的“高度”属性。 因为它是自动设置的。

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

使用 vw(viewport width) 和 vh(viewport height) 代替 px

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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