簡體   English   中英

如何根據屏幕尺寸在div中縮放背景圖像

[英]How to scale a background image in a div responsively to the screen size

我想在div內的網站上添加背景圖片,該圖片應在所有設備上完美調整大小。 我嘗試了最簡單的方法,例如“高度:100%”,但這根本沒有用。 我還嘗試了媒體查詢,該方法當然可以工作,但是相當復雜,所以我想問一下是否有更簡單的方法來解決這個問題。

這是HTML

<div class="bg"></div>

那就是CSS

.bg {
    background: url('bg.jpg') no-repeat center cover;
}

我仍在學習自己,但是您是否嘗試過“背景尺寸:封面;” 在您的CSS中?

在此處查看更多信息: https : //www.w3schools.com/cssref/css3_pr_background-size.asp

只需將大小首選項應用於背景屬性即可。 這是一種簡寫用法:

這是大背景圖片的設置,背景圖片填充了其父邊框。

background: url('images/image.jpg') no-repeat center center/cover;

等於:

background-image: url('images/image.jpg');
background-repeat: no-repeat;
background-position: center;
background-size: cover;

我建議對此MDN線程進行讀取。

我剛剛發現,您確實可以使用“ height”並將其設置為100 ,但不能使用'%' ,而可以使用'vh'

height: 100vh;

@Sqnkov有正確的答案。 空div將適用於該設置。

嘗試運行下面的代碼,看看。 (將其整頁顯示並調整瀏覽器大小)。 center center ,使在Y和X軸為中心。 background-size: cover; 使圖像覆蓋所有可用空間。 如果要確保查看整個圖像,請使用background-size: contain; 代替。

 body{ margin: 0; /* Stripping out margin and padding so .bg can be full width*/ padding: 0; } .bg { box-sizing: border-box; /*Not necessary in this situation*/ display: block; /*Not necessary, but we do want it this way*/ width: 100vw; /*Not necessary, but we do want it this way*/ height: 100vh; /*Necessary. 100vh = 100% of the viewport height*/ padding: 0; /* No padding */ margin: 0; /* No margins */ background: url('https://images6.alphacoders.com/405/405948.jpg') no-repeat center center; /* Shorthand: image, repeat, X align, Y align. */ background-size: cover; /* Cover all available space*/ } 
 <div class="bg"></div> 

另外,如果您指定父容器的( html, body )高度和寬度為100%,則可以在子.bg容器上使用100%高度/寬度而不是100vh/vw ,因為百分比是相對於父容器的百分比。

請參閱以下示例:

 html, body{ margin: 0; /* Stripping out margin and padding so .bg can be full width*/ padding: 0; width: 100%; /*Setting parent width -- child width is relative*/ height: 100%; /*Setting parent height -- child height is relative*/ } .bg { box-sizing: border-box; /*Not necessary in this situation*/ display: block; /*Not necessary, but we do want it this way*/ width: 100%; height: 100%; /* Now 100% height will work */ padding: 0; /* No padding */ margin: 0; /* No margins */ background: url('https://images6.alphacoders.com/405/405948.jpg') no-repeat center center; /* Shorthand: image, repeat, X align, Y align. */ background-size: cover; /* Cover all available space*/ } 
 <div class="bg"></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM