Title-safe 覆盖背景图片

Title-safe covering background image

一段时间以来,我们拥有令人敬畏的 background-size: coverbackground-size: contain CSS 属性。

我正在寻找的是一种实现两者结合的方法。让我们称之为 'title-safe' 区域。

基本上在我的背景中,每个轴上都有一个区域,如果它 disappears/crops 如果边界框的大小不合适,则没有问题,但是有一个内部区域绝对必须可见,我们可以使用信箱来确保这是真的。

更多信息:

这些 4:3 和 16:9 比率内的内框是一个 266.666 x 168.75 像素的区域。我想确保如果人们以 other/weirder 宽高比观看图像,那么内部区域始终保持可见,我将其称为 'title safe area'.

您可以有 3 种不同的样式,并根据宽高比使用媒体查询更改它们

我还更改了边框颜色,以便很容易知道适用哪种样式

html, body {
  height: 100%;
}

.test {
  width: 90%;
  height: 90%;
  border: solid 2px black;
  margin: auto;
  background: url(http://i.stack.imgur.com/ZmhEE.jpg);
  background-position: center;
  background-repeat: no-repeat;
  background-size: contain;   /* changed by media queries */
}

@media screen and (min-aspect-ratio: 16/9) { 
  .test {
      border: solid red 2px; 
      background-size: auto 120%;
  }
}
@media screen and (max-aspect-ratio: 4/3) { 
   .test {
        border: solid green 2px;
        background-size: 120% auto;
    }
}
<div class="test"></div>

我想通了。

以 html 文档为例:

<div class="container">
  <div class="inner">
  </div>
</div>

inner css class 将获得始终处于 3:2 宽高比的背景图像。

容器具有以下 CSS 规则。请注意,此处的宽度和高度是静态的,但它们可以具有 任何 值,包括百分比。您可以调整它们以确保系统正常工作。

.container {
   width: 900px;
   height: 450px;
   overflow: hidden;
 }

然后内部 css 需要以下规则才能正确运行:

.inner {
  /* Set the background image. Must be 3:2 aspect ratio! */
  background-image: url('background.jpg');

  /* Fill up the container.*/
  width: 100%;
  height: 100%;

  /* This is the default in any browser, but many people set it to
     border-box these days for every element. It must be "content-box"
     for this to work. The key thing here is that the width/height
     cannot include the padding.
   */
  box-sizing: content-box;

  /* Normal CSS contain behavior */
  background-size: contain;
  background-repeat: no-repeat;

  /* Always go to the center */
  background-position: center center;

  /* This will cause the background to extend beyond the content and
     into the padding.
   */
  background-clip: padding-box;

  /* These numbers are just based on trial and error and not exact.
     I tried to figure it out with Math, but my math was wrong. These
     are fairly close approximations.

     Effectively the width + the padding becomes the total 3:2 image
     and the total image MINUS the padding = the title safe area.
   */
  padding: 6% 8% 6% 8%;

  /*
     These margins ensure that the image is still centered.
     The overflow:hidden on the container element make sure that
     there's no scrollbars.
   */
  margin-left: -8%;
  margin-top: -6%;

}