2016-09-18 170 views
5

我在https://jsfiddle.net/ncrcfduz處有以下代碼,並且在https://s21.postimg.org/iq2mtjaiv/bg_boardwalk.jpg處有背景圖像。我需要將背景圖像重新縮放以適合div,並首選顯示圖像中大部分「居中」的內容。以下代碼僅顯示圖像的左上角。CSS背景圖像 - 縮小以適合固定大小div

.container { 
 
    background: url(https://s21.postimg.org/iq2mtjaiv/bg_boardwalk.jpg) no-repeat fixed; 
 
    -webkit-background-size: cover; 
 
    -moz-background-size: cover; 
 
    -o-background-size: cover; 
 
    background-size: cover; 
 
    height: 150px; 
 
    width: 300px; 
 
}
<div class="container"> 
 
</div>

+0

你所說的 「中心」 的內容是什麼意思? –

+1

使用background-size:包含。 – kinakuta

+0

這是相關的:http://stackoverflow.com/questions/21786272/css-background-size-cover-background-attachment-fixed-clipping-background-im 與'background-attachment:fixed'圖像的大小相對於視口,不包含元素。 –

回答

13

您正在尋找background-size: containsee the css-tricks' entry),不cover。爲了讓你的例子工作,你必須刪除background-attachment: fixed。使用background-position: center將背景放在您的div中。

.container{ 
 
    background: url(https://s21.postimg.org/iq2mtjaiv/bg_boardwalk.jpg) no-repeat center; 
 
    -webkit-background-size: contain; 
 
    -moz-background-size: contain; 
 
    -o-background-size: contain; 
 
    background-size: contain; 
 
    
 
    height: 150px; 
 
    width: 300px; 
 
}
<div class="container"> 
 
</div>

1

你只需要在你的 「背景」 命令替換爲 「固定」,由 「中心」。

就像是:

background: url(https://s21.postimg.org/iq2mtjaiv/bg_boardwalk.jpg) no-repeat center; 

的jsfiddle這裏:https://jsfiddle.net/ncrcfduz/2/

0

你應該使用:

.container{ 
    background-size: 100%; 
}