当封面背景大小和位置绝对的背景图像停止调整大小时?

时间:2018-05-23 19:51:47

标签: html css

我们假设我们将图像设置为div的背景。 divposition: absolute。图像处于background-size: cover模式。在这种情况下,背景图像将被调整大小。但在某些时候,在某种程度上,背景图像的宽度和高度将是相同的。

如何计算图像停止调整大小的尺寸?

它与图像的宽度或高度没有直接关系,也与容器没有直接关系。我无法找到任何关于它的文档。

CSS

.bg {
  background-image: url("http://www.adweek.com/wp-content/uploads/files/blogs/istock-unfinished-business-hed-2015.jpg");
  width:100%;
  height:100%;
  background-size:cover;
  background-repeat: no-repeat;
  position:absolute;
}

HTML

<body>
    <div class="bg"></div>
</body>

的jsfiddle

https://jsfiddle.net/fbng74dm/

更新

一些示例值(近似值):

  • 容器高度976
  • 容器停止调整宽度为1540的背景图片
  • 容器高度729
  • 容器停止调整宽度为1147的背景图片
  • 容器高度643
  • 容器停止调整宽度为1010的背景图片
  • 背景图片身高2827
  • 背景图片宽度4465

2 个答案:

答案 0 :(得分:2)

如果宽度较大,则图像会缩放,因此无法看到图像的整个高度。减小容器的尺寸越大,容纳在容器中的高度越大。一旦人们可以看到整个高度,图像就不应再调整大小,因为它不会覆盖容器。

为什么呢?让我们看一个不停止调整背景图像大小的示例:

&#13;
&#13;
var aspectRatio = 1920 / 1280;
var bg = document.getElementsByClassName('bg')[0];
window.addEventListener('resize', resizeListener);

function resizeListener() {
	if (bg.offsetWidth / bg.offsetHeight <= aspectRatio) {
  	bg.className = 'bg small';
  } else {
  	bg.className = 'bg';
  }
}
&#13;
* {
  margin: 0;
  padding: 0;
}

.bg {
  background-image: url("http://www.adweek.com/wp-content/uploads/files/blogs/istock-unfinished-business-hed-2015.jpg");
  width: 100%;
  height: 100%;
  background-size: cover;
  background-repeat: no-repeat;
  position: absolute;
}

.small {
  background-size: contain;
}
&#13;
<div class="bg">
</div>
&#13;
&#13;
&#13;

JSFiddle上试用!

您看,背景图片不再覆盖整个背景,但我们设置了background-size: cover;。这就是它保持高度并从侧面突出的原因。

什么时候到达这一点?正如您在我的代码示例中已经看到的那样,一旦容器的纵横比变得小于背景图像的纵横比,就会达到该点。原因很简单:没有其他可能性。尝试一下,你将无法以不同的方式进行。这有简单的实际原因。

答案 1 :(得分:0)

当屏幕达到一定宽度时,您可以使用@media查询使背景大小停止为cover。例如:

.bg {
  background-image: url("http://www.adweek.com/wp-content/uploads/files/blogs/istock-unfinished-business-hed-2015.jpg");
  width:100%;
  height:100%;
  position:absolute;
}
@media(max-width: 600px){
  .bg{
    background-size:cover;
    background-repeat:no-repeat;
  }
}
@media(min-width: 601px){
  .bg{
     background-size:auto;
   }
}

这意味着最大宽度为600px (即当窗口宽度为600px或更小时),背景为cover降至最小宽度为601px (即当窗口宽度为601px或更大时)背景为auto

相关问题