获取CSS背景大小:覆盖比例百分比

时间:2019-03-15 23:51:36

标签: css css3

我需要弄清楚图像的缩放比例。

我正在使用body将背景图像设置为background-size: cover。基本上,无论屏幕大小是多少,图像都将始终保持其纵横比并扩大(或缩小),直到它填满屏幕的宽度和高度。然后,它将定位自己,使其在垂直和水平方向居中,并裁剪掉“多余”的东西。

假设我知道 1)原始背景图片尺寸 2)屏幕/视口站点

如何确定图像实际缩放了多少?

1 个答案:

答案 0 :(得分:2)

如果我们假设您的图片尺寸为WxH,并且屏幕尺寸为AxB,那么它应该是A/WB/H之间的最大值。

一些例子:

.box {
  width:400px;
  height:200px;
  background:url(https://picsum.photos/300/300?image=0) center/cover;
}
/*
we will have 1.333 = 400/300 and 0.6667 = 200/300
*/
img {
 transform:scale(1.3333);
 transform-origin:top left;
}
<div class="box">

</div>
<img src="https://picsum.photos/300/300?image=0">

.box {
  width:300px;
  height:200px;
  background:url(https://picsum.photos/500/500?image=0) center/cover;
}
/*
we will have 0.6 = 300/500 and 0.4 = 200/500
*/
img {
 transform:scale(0.6);
 transform-origin:top left;
}
<div class="box">

</div>
<img src="https://picsum.photos/500/500?image=0">

.box {
  width:100px;
  height:300px;
  background:url(https://picsum.photos/400/300?image=0) center/cover;
  display:inline-block;
}
/*
we will have 0.25 = 100/400 and 1 = 300/300
*/
img {
 transform:scale(1);
 transform-origin:top left;
}
<div class="box">

</div>
<img src="https://picsum.photos/400/300?image=0">

对于contain,我们取最小值:

.box {
  width:400px;
  height:200px;
  background:url(https://picsum.photos/300/300?image=0) left/contain no-repeat;
}
/*
we will have 1.333 = 400/300 and 0.6667 = 200/300
*/
img {
 transform:scale(0.6667);
 transform-origin:top left;
}
<div class="box">

</div>
<img src="https://picsum.photos/300/300?image=0">

.box {
  width:300px;
  height:200px;
  background:url(https://picsum.photos/500/500?image=0) left/contain no-repeat;
}
/*
we will have 0.6 = 300/500 and 0.4 = 200/500
*/
img {
 transform:scale(0.4);
 transform-origin:top left;
}
<div class="box">

</div>
<img src="https://picsum.photos/500/500?image=0">

.box {
  width:100px;
  height:300px;
  background:url(https://picsum.photos/400/300?image=0) top/contain no-repeat;
  display:inline-block;
}
/*
we will have 0.25 = 100/400 and 1 = 300/300
*/
img {
 transform:scale(0.25);
 transform-origin:top left;
}
<div class="box">

</div>
<img src="https://picsum.photos/400/300?image=0">