【问题标题】:CSS background image - shrink to fit fixed size divCSS 背景图像 - 缩小以适合固定大小的 div
【发布时间】:2016-09-18 15:59:18
【问题描述】:

我在https://jsfiddle.net/ncrcfduz 有以下代码,在https://s21.postimg.org/iq2mtjaiv/bg_boardwalk.jpg 有一个背景图像。我需要重新调整背景图像以适合 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>

【问题讨论】:

  • “居中”内容是什么意思?
  • 使用 background-size: contains 代替。
  • 这是相关的:stackoverflow.com/questions/21786272/…background-attachment: fixed 图像的大小相对于视口,不包含元素。

标签: css background background-image


【解决方案1】:

您正在寻找background-size: contain (see the MDN entry),而不是cover。要使您的示例正常工作,您必须删除background-attachment: fixed。使用background-position: centerdiv 中的背景居中。

.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: &lt;background-position&gt;/&lt;background-size&gt;。看起来像

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

    height: 150px;
    width: 300px;
}

【讨论】:

    【解决方案2】:

    你应该使用:

    .container{
        background-size: 100%;
    }
    

    【讨论】:

      【解决方案3】:

      您只需在“背景”指令中将“固定”替换为“中心”即可。

      像这样:

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

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

      【讨论】:

        【解决方案4】:
        .container{
            background-size: contain;
        }
        

        【讨论】:

          【解决方案5】:

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

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

          【讨论】:

            猜你喜欢
            • 2015-11-13
            • 2015-05-06
            • 2015-07-30
            • 2013-02-25
            • 1970-01-01
            • 1970-01-01
            • 2012-07-19
            • 1970-01-01
            • 2013-09-01
            相关资源
            最近更新 更多