2017-09-11 29 views
4

我有以下的HTML代碼:當background-position:center指定背景圖像部分移出窗口時;

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Document</title> 
    <link rel="stylesheet" type="text/css" href="1.css"> 
</head> 
<body> 

<body> 

我的CSS代碼如下:

body { 
    background-image: url(tree.png); 
    background-repeat: no-repeat; 
    background-position: center; 
} 

現在我的谷歌Chrome瀏覽顯示以下的輸出:

enter image description here

這裏,圖像樹位於頂部中心,部分位於窗口外。

爲了改善這種情況我改變我的CSS代碼如下:

body { 
     background-image: url(tree.png); 
     background-repeat: no-repeat; 
     background-position: center; 
     margin-top: 600px; 
    } 

現在我的瀏覽器顯示的輸出如下:

enter image description here

我的問題是,爲什麼我要補充保證金在頂部和背景圖像是不是默認去我的瀏覽器頁面的中心?

回答

3

這與文檔的高度有關。沒有內容,身高就達到最小值。如果你改變你的CSS以下內容,背景圖像應該是中央:

html { 
    background-image: url(tree.png); 
    background-repeat: no-repeat; 
    background-position: center; 
    height:100%; 
} 

https://jsfiddle.net/z85ony88/

此外,如果你需要對身體的背景圖像。使用以下內容:

html { 
    height:100%; 
} 
body { 
    background-image: url(https://jsfiddle.net/img/logo.png); 
    background-repeat: no-repeat; 
    background-position: center; 
} 
2

這是因爲你的身體沒有足夠的高度來顯示完整的圖像。通過爲身體設置身高,或者身體上有足夠的內容可以解決問題。檢查下面的代碼段。在這裏,我設置了height: 100vh來覆蓋屏幕,在全屏視圖中檢查它。

body { 
 
    background-image: url(https://beebom-redkapmedia.netdna-ssl.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg); 
 
    background-position: center; 
 
    background-repeat: no-repeat; 
 
    height: 100vh; 
 
}
<body> 
 

 
</body>

+0

是什麼'vh'單位? – Sonevol

+1

@Sonevol它的視口高度 – VilleKoo