从一段时间以来,我们拥有了令人敬畏的background-size: cover
和background-size: contain
CSS属性。
我正在寻找的是一种实现两者结合的方法。让我们称之为'标题安全'区域。
基本上在我的背景中,每个轴上都有一个区域,如果它消失/庄稼,如果边界框不合适的大小,但是内部区域绝对必须可见,我们可以使用信箱确保这是真的。
更多信息:
这4:3和16:9比例内的内框是266.666 x 168.75像素的面积。我想确保如果人们在其他/更奇怪的长宽比上观看图像,内部区域始终保持可见,我将其称为“标题安全区域”。
答案 0 :(得分:0)
您可以拥有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>
&#13;
答案 1 :(得分:0)
我明白了。
以html文档为例:
<div class="container">
<div class="inner">
</div>
</div>
inner
css类将获得一个始终为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%;
}