2017-03-22 97 views
0

我想知道我在使用background-image屬性時做了什麼錯誤,我希望圖片始終以完全調整大小的方式顯示在它的父級div上(no它會顯示什麼樣的分辨率),這裏是我到目前爲止的內容,我完全意識到問題不是那麼複雜,但我無法完成它!謝謝你的幫助。css div + background-image

body { 
 
    margin: 0px; 
 
} 
 

 
header { 
 
    height: 200px; 
 
    background-image: url(http://kingofwallpapers.com/picture/picture-008.jpg); 
 
    background-size: cover; 
 
}
<header> 
 
</header>

回答

5

你靠近。你只需要設置背景大小來包含。 contain縮放背景圖像父尺寸(不拉伸,即最小,寬度或高度。)

background-repeat僅僅是不一遍遍重複背景

body { 
 
    margin: 0px; 
 
} 
 

 
header { 
 
    height: 200px; 
 
    background-image: url(http://kingofwallpapers.com/picture/picture-008.jpg); 
 
    background-size: contain; 
 
    /* background-size: 100% 100%; <- stretch fit to parent */ 
 
    background-repeat: no-repeat; 
 
}
<header> 
 
</header>

+0

你能爲你的答案的解釋? –

+0

@CameronRoe完成 – mehulmpt

+0

以及如果我想讓圖片在保持其原始高度的同時具有100%的寬度?謝謝你的答案btw。 –

0

而不是

background-size: cover; 

您應該使用:

background-size: 100% 100%; 

所以我覺得這個代碼可以幫助:

body { 
 
    margin: 0px; 
 
} 
 

 
header { 
 
    height: 200px; 
 
    background-image: url(http://kingofwallpapers.com/picture/picture-008.jpg); 
 
    background-size: 100% 100%; 
 
}
<header> 
 
</header>