我想在我的網站中添加一個背景圖像,該div應該在所有設備上完美調整大小。我嘗試了最簡單的方法,比如「身高:100%」,但根本不起作用。我也嘗試了媒體查詢,當然這些查詢很有用,但是相當複雜,所以我想問問是否有更簡單的方法來解決這個問題。如何根據屏幕尺寸縮放div中的背景圖像
這裏的HTML
<div class="bg"></div>
這就是今天的CSS
.bg {
background: url('bg.jpg') no-repeat center cover;
}
我想在我的網站中添加一個背景圖像,該div應該在所有設備上完美調整大小。我嘗試了最簡單的方法,比如「身高:100%」,但根本不起作用。我也嘗試了媒體查詢,當然這些查詢很有用,但是相當複雜,所以我想問問是否有更簡單的方法來解決這個問題。如何根據屏幕尺寸縮放div中的背景圖像
這裏的HTML
<div class="bg"></div>
這就是今天的CSS
.bg {
background: url('bg.jpg') no-repeat center cover;
}
@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%則可以使用100%
高度/寬度,而不是100vh/vw
子.bg
容器上如百分數均以相對於父容器。
請參見下面的例子: '?在所有設備上完美地調整'
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>
非常感謝! – Timo
沒問題!當你可以運行它時,更容易想象它:D我真的很喜歡,所以讓我們嵌入代碼片段。無論如何,如果這回答了您的問題,您可以將此標記爲已接受答案* wink-wink *; p – StephanieQ
我還在學習自己,但你嘗試過 「背景大小:覆蓋;」在你的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;
我建議給this MDN thread讀。
你什麼意思 - 設備具有不同的寬高比。 – sol
是的,這是重點。是不是有一種簡單的方法讓背景圖像調整自己獨立於設備的屏幕大小? – Timo
我會詳細說明...您如何讓橫向照片以縱向模式在移動設備上進行觀看?你想要它覆蓋整個屏幕並居中? – sol