CSS 背景图片 - 缩小以适合固定大小 div

CSS background image - shrink to fit fixed size div

我在 https://jsfiddle.net/ncrcfduz, and a background image at https://s21.postimg.org/iq2mtjaiv/bg_boardwalk.jpg 处有以下代码。我需要重新缩放背景图像以适应 div,最好显示图像中的大部分 "centered" 内容。以下代码只显示图片的左上角。

.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>

您只需在 "background" 指令中将 "fixed" 替换为 "center"。

像那样:

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

JSFiddle 在这里:https://jsfiddle.net/ncrcfduz/2/

你应该使用:

.container{
    background-size: 100%;
}

您正在寻找 background-size: contain (see the MDN 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>

备注:

  • 现在你几乎肯定不需要浏览器前缀,这意味着你可以只使用 background-size: contain。参见 https://developer.mozilla.org/en-US/docs/Web/CSS/background-size#Browser_compatibility

  • 如果您使用 Autoprefixer(包含在许多构建工具和构建设置中),它将自动为您添加任何必要的前缀版本,这意味着您可以 background-size: contain即使当前版本的主要浏览器仍然需要前缀。

  • 您可以使用语法 background: <background-position>/<background-size>background shorthand 属性 中包含大小。看起来像

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

    height: 150px;
    width: 300px;
}
.container{
    background-size: contain;
}

我是这样解决的。您可以这样设置您的代码:

<div style="background-image: url('your_url') ;background-size: 100% 100%; "> <div>

这个技巧应该有用,但默认情况下它不会保持图像纵横比。

background-size: 100% 100%;