css - 使用背景大小:cover?时如何获取图像的比例百分比

标签 css background

我需要弄清楚图像缩放了多少。

我正在使用 background-size: coverbody 设置背景图像。

基本上,无论屏幕尺寸如何,图像都会始终保持其宽高比并扩大(或缩小)直到它填满屏幕的宽度和高度。然后它会自行定位,使其垂直和水平居中,“多余”部分被裁剪掉。

假设我知道

  1. 原始背景图片大小
  2. 屏幕/视口(viewport)站点

我怎样才能知道图像实际缩放了多少?

最佳答案

如果我们假设您的图像尺寸为 WxH 并且屏幕尺寸为 AxB 那么它应该是 A/W 之间的最大值> 和 B/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">

关于css - 使用背景大小:cover?时如何获取图像的比例百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55800201/

相关文章:

css - Bootstrap - 在 bootstrap 3 中只显示两个字形

html - 如何使用 html 和 CSS 布置所需的设计?

css - 以编程方式使用 sass 嵌套规则

html - 在 IE8 中,当高度高于窗口时,ms-filter 背景消失。 (当出现滚动条时)

css:仅当链接在特定类中时才对链接执行特定操作

javascript - 在 slickgrid 中新建分页工具栏

css - 元素背景图像不会呈现

css - yslow 在多个背景上失败?

css - Susy 网格中部分的全尺寸背景

ios - 触摸 ScrollView 时隐藏键盘