I need to figure out how much an image has scaled.
I am setting a background image to the body
with the background-size: cover
.
Basic
If we suppose your image has a dimension of WxH
and the screen size is AxB
then it should be the biggest value between A/W
and B/H
.
Some examples:
.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">
With contain
we take the smallest value:
.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">