2016-09-18 171 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%; 
}