2017-04-15 78 views
0

我想在我的body中使用背景圖像。背景圖像應該覆蓋視口(與屏幕寬度和高度相同)。我有以下代碼,但背景圖像比視口/屏幕顯示得更高:圖像底部向下延伸。這可能是因爲背景圖像沒有被身體100%的高度裁剪。背景大小:身體覆蓋高於視口(即使身體高度爲100%)

html { 
 
    \t height:100%; 
 
     } 
 
    
 
    body { 
 
     \t height:100%; 
 
    \t background-image:url("http://lorempixel.com/400/200/"); 
 
    \t background-position: top left; 
 
    \t background-size:cover; 
 
    \t background-repeat:no-repeat; 
 
    \t } 
 
    
 
    main { 
 
    \t max-width:80rem; 
 
    \t height:1000px; 
 
    \t background-color: rgba(0,0,200,0.5); 
 
    \t }
<main></main>

+0

@vals注意到你刪除答案,你知道它爲什麼會這樣嗎? – LGSon

+0

我相信有一個特殊情況與身體背景,我認爲有一個關於這個問題的地方,但我一直沒有找到它 – vals

回答

2

我認爲,這種現象的原因是規格的這一部分:

根元素的背景變得畫布的背景,並覆蓋整個畫布,錨定(關於「背景位置」)在如果僅爲根元素本身繪製的話,它將會是相同的點。根元素不會再次繪製該背景。

因此,這將是一個特別的問題與

在這個片段中,一個 - 僞正常工作

html, 
 
body { 
 
    height: 100%; 
 
} 
 

 
body::before { 
 
    content: ''; 
 
    position: absolute; 
 
    left: 0; 
 
    top: 0; 
 
    width: 100%; 
 
    height: 100%; 
 
    background-image: url("http://lorempixel.com/400/600/"); 
 
    background-position: top left; 
 
    background-size: cover; 
 
    background-repeat: no-repeat; 
 
    z-index: -1; 
 
} 
 

 
main { 
 
    max-width: 80rem; 
 
    height: 1000px; 
 
    background-color: rgba(0, 0, 200, 0.5); 
 
}
<main></main>

+0

我刪除了我的信息並更新了你的信息,再加上1 ...希望你不介意:) – LGSon

+0

@LGSon當然我不介意:-)但是你的回答是可以的,我不想發佈我的信息作爲替代方案,只是想明確這個問題是圍繞* body *的一個特例。無論如何,這樣很好。 ...並感謝:-) – vals

0

可以應用一個最小寬度和最小高度,以在主體100。

視口下面的測量

body { 
 
    height:100%; 
 
    min-width:100vw; 
 
    min-height:100vh; 
 
    background-image:url("https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSnfXp5RSFk2ZfOmIl7EMvUHEW0bzWBowc6NtDFkG3M7r2Xljl2"); 
 
    background-position: top left; 
 
    background-size: cover; 
 
    background-repeat:no-repeat; 
 
    margin:auto; 
 
    }
<body> 
 
<main> 
 
</main> 
 
</body

看看代碼段
+0

這並不能阻止它被裁剪當高度低於圖像的比率高度....這有道理嗎? – LGSon