背景尺寸封面/中心不起作用

Sil*_*fer 2 html css twitter-bootstrap

我尝试使用background-size: cover和将背景图像置于 div 中心background-size: contain,但它不起作用。我需要在 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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Gez*_*asa 7

你的.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;
 }
Run Code Online (Sandbox Code Playgroud)

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

背景大小将放大图像,直到整个 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;
 }
Run Code Online (Sandbox Code Playgroud)