背景大小的封面/中心不起作用

新手上路,请多包涵

我正在尝试使用 background-size: coverbackground-size: contain 将背景图像居中到 div,但它不起作用。我需要在 HTML 标签内显示背景图片并在 css 文件中使用背景大小,这是代码:

 .container {
    width: 200px;
    height: 260px;
    position: relative;
    margin: 0 auto 40px;
    margin-left: 20px;
    display: inline-block;
}
.main{
    border: 1px solid black;
    background-color: #A6A6A6;
}
.card {
    width: 100%;
    height: 100%;
    position: absolute;
    border: 2px solid white;
}
.card div {
    height: 100%;
    width: 100%;
    color: white;
    text-align: center;
    position: absolute;
}
.card .front {
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
    -webkit-background-size: contain;
    -moz-background-size: contain;
    -o-background-size: contain;
}
 <body style="background-image:url(https://s3.amazonaws.com/Syntaxxx/background-gold-bokeh.jpg);">
<div class="main">
  <section class="container">
      <div class="card">
          <div class="front" style="background-image: url('http://www.mobygames.com/images/covers/l/403626-injustice-2-playstation-4-front-cover.png');">
          </div>
          <div class="back">1</div>
      </div>
  </section>
  <section class="container">
      <div class="card">
          <div class="front" style="background-image: url('http://www.mobygames.com/images/covers/l/403651-the-surge-playstation-4-front-cover.jpg');">
          </div>
          <div class="back">2</div>
      </div>
  </section>
</div>

</body>

原文由 SilverSurfer 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 322
2 个回答

您的 .card .front 的样式为 background-repeat 您为其赋予了太多属性。

center center 需要给 background-position

 .card .front {
     background-position: center center;
     background-repeat: no-repeat;
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover;
 }

对于 CSS 和大多数其他维度,您使用 X 然后 Y 然后 Z(除了 Z-index 之外没有 Z)

background-size 会放大图片直到填满整个 div。

您正在寻找的是 background-size: contain 。这将在任何容器中显示完整图像。然后添加 center center

 .card .front {
    background-image: url(https://s3.amazonaws.com/Syntaxxx/background-gold-bokeh.jpg);
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
    -webkit-background-size: contain;
    -moz-background-size: contain;
    -o-background-size: contain;
 }

原文由 Gezzasa 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是一个简单的修复,您需要指定 background-position: center; 。这将确保您的背景图片居中。

 .card .front {
    background-position: center;
}

原文由 Vincent1989 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题