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

标签 html twitter-bootstrap css

我尝试使用 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>

最佳答案

您的 .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;
 }

关于html - 背景大小的封面/中心不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47324360/

相关文章:

html - 背景不透明度

javascript - CSS/SVG/动画 : Apply transform origin to a single element within svg not working

html - CSS 在另一个文本上书写文本

css - 列表的 Angular 指令和 ng-repeat;不继承父类

html - 当折叠的元素很长时 Accordion 跳跃

javascript - Jquery on keyup 一次

javascript - jquery 在滚动上切换类

javascript - 占位符上的 Select2 Font Awesome 图标

javascript - 使 highcharts 中的标题可点击并使用 bootstrap popover?

css - Puppeteer - 无法在酒店网站中拉出正确的 CSS 选择器