2016-11-08 115 views
0

我無法居中背景。無論我是否將BG改爲小尺寸以使其居中,都不會。CSS背景位置不會居中

她是我的CSS:

#container {  
    background-image: url(Photos/BG.png); 
    background-repeat:no-repeat; 
    background-position: center center; 
    height: 1813px; 
    width: 1024px; 
} 

它不居中的背景 - 它一直持續到顯示器的左上角,即使使用較小尺寸的照片。謝謝你們!

+2

你的代碼工作,你會期望。可能存在不同的CSS規則干擾。 –

+0

問題是** **您的CSS沒有加載,**或**您與其他標記/樣式有衝突。你可以在[這個jsFiddle](https://jsfiddle.net/cale_b/r3fpg8nn/)中看到你的css工作得很好。 –

+0

起初我把一個'中心'仍然不起作用。但我現在有一個解決方案,把margin:auto;它將以任何分辨率自動居中。謝謝您的回覆。 – artoo

回答

-1
background-image: url(path-to-file/img.jpg); 
background-repeat:no-repeat; 
background-position: center center; 

應該工作,你可以做的一件事就是讓一個div並把IMG在裏面,然後用-1 z-index的,只是居中DIV。

您也可以嘗試加入

body { 
    min-height: 100%; 
} 

,因爲容器可能不是完整的視口大小。

+0

謝謝你的時間先生。我沒有嘗試把Z指數。我的解決方案是把邊距作爲自動。 – artoo

0

要集中背景圖像,您不需要指定兩次中心。它應該是如下:

#container {  
    background-image: url(Photos/BG.png); 
    background-repeat:no-repeat; 
    background-position: center; 
    height: 1813px; 
} 
+0

這不是真正**問題的答案**,這是一個*可選方法*來指定中心/中心(無論是「中心中心」還是「中心」都是有效選項) –

+0

起初,我把一個'中心'仍然不起作用。但我現在有一個解決方案,把margin:auto;它將以任何分辨率自動居中。謝謝您的回覆。 – artoo

0

你的代碼工作aspected,如果您刪除的寬度,你會清楚地看到在後臺中心的形象...

<!DOCTYPE html> 
<html lang=""> 
<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <title></title> 
    <style> 
     #container {  
    background-image: url('http://supermario3dworld.nintendo.com/_ui/img/views/power-ups/char-dobble-mario.png'); 
    background-repeat: no-repeat; 
    background-position: center; /* you dont need to specify the value two times */ 
    height: 1813px; 

      background-color: aquamarine; 
} 
    </style> 
</head> 

<body> 
    <div id="container"> 

    </div> 
</body> 
</html> 
+0

爲什麼要刪除寬度?這不應該被要求。 –

+0

只能看到背景居中,它會居中每個寬度 – DaFois

+0

謝謝你的答覆先生。欣賞它。但如果我刪除寬度的BG照片會擴大,或者它會拉伸,從而使BG有點奇怪。但我已經通過將margin設置爲auto來找到解決方案。非常感謝。即時學習。 – artoo