簡體   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