[英]How do I get my header image to fill the width whilst keeping same height and aspect ratio?
[英]How do I increase my image width and height according to the viewport of the user while keeping the aspect ratio same?
我正在制作一個網站,該網站基本上只是一個巨大的圖像,除了可點擊的元素,我想知道如何根據用戶的屏幕尺寸增加圖像尺寸,以便圖像看起來不會被拉伸,但是仍然適合整個屏幕。 這是我第一次使用視口,所以我不能說我非常理解它。 這里有一些代碼可以提供幫助:
<div class="Image">
<img src="Background.png"/>
</div>
.Image {
width: 100vw;
height: 100vh;
object-fit: contain;
}
第一部分是用 index.html 編寫的,而第二部分是用 style.css 編寫的。 僅供參考,html 部分是用<body>
編寫的。
<div class="fullscreen" />
.fullscreen {
position: fixed;
top: 0;
left: 0;
background-image: url(Background.png);
background-size: cover;
background-position: center;
width: 100vw;
height: 100vh;
}
你必須申請
width: 100vw;
height: 100vh;
object-fit: contain;
直接img
可以直接使用id
class
或img
但不推薦使用 last 方法,因為它將適用於文檔中的所有img
標簽
我使用red
background
來顯示圖像覆蓋了多少區域,但作為object-fit: contain;
所以圖像比例保持不變
閱讀此內容以了解有關object-fit
更多信息
用
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
刪除任何不必要的horizontal
滾動條,因為標簽有一些默認的margin
和padding
。 所以,這里使用了body
標簽
.Image { width: 100vw; height: 100vh; object-fit: contain;/*Can be cover , fill , none...*/ background-color: red; } body { box-sizing: border-box; margin: 0; padding: 0; }
<div> <img src="https://www.hdnicewallpapers.com/Walls/Big/Rainbow/Rainbow_on_Mountain_HD_Image.jpg" class="Image" /> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.