2017-03-07 74 views
1

我想在我的網站中添加一個背景圖像,該div應該在所有設備上完美調整大小。我嘗試了最簡單的方法,比如「身高:100%」,但根本不起作用。我也嘗試了媒體查詢,當然這些查詢很有用,但是相當複雜,所以我想問問是否有更簡單的方法來解決這個問題。如何根據屏幕尺寸縮放div中的背景圖像

這裏的HTML

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

這就是今天的CSS

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

你什麼意思 - 設備具有不同的寬高比。 – sol

+0

是的,這是重點。是不是有一種簡單的方法讓背景圖像調整自己獨立於設備的屏幕大小? – Timo

+0

我會詳細說明...您如何讓橫向照片以縱向模式在移動設備上進行觀看?你想要它覆蓋整個屏幕並居中? – sol

回答

1

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

+0

非常感謝! – Timo

+0

沒問題!當你可以運行它時,更容易想象它:D我真的很喜歡,所以讓我們嵌入代碼片段。無論如何,如果這回答了您的問題,您可以將此標記爲已接受答案* wink-wink *; p – StephanieQ

1

只需將大小首選項應用於背景屬性。下面是一個速記用法:

這是充滿其父到邊框的大背景圖像的設置。

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讀。

+0

謝謝。但是當我的背景圖像在div裏面時它有什麼不同嗎?因爲背景僅在**內部有**時才顯示,就像文本一樣。但是我希望背景圖像縮放到獨立於屏幕大小,而不管div是否有內容。 – Timo

+0

您是否嘗試過上述方法? – snkv

+0

是的,但正如我所說,背景圖像是在一個div內。這有什麼區別嗎? – Timo

1

我剛剛發現,你可以使用「高度」的確並將其設置爲,但不「%」「VH」

height: 100vh; 
+1

您還可以使用'vw'(視口寬度)設置寬度。但是當涉及到頁面的其他部分時,'vh'和'vw'都會導致一些不想要的行爲。 – snkv

+0

好吧,不知道,並會繼續關注它。但它不適用於'%'或'px'。有沒有其他的單位不會有什麼麻煩? – Timo