Scale div with its content to fit window
let outer = document.getElementById('outer'),
wrapper = document.getElementById('wrap'),
maxWidth = outer.clientWidth,
maxHeight = outer.clientHeight;
window.addEventListener("resize", resize);
resize();
function resize(){let scale,
width = window.innerWidth,
height = window.innerHeight,
isMax = width >= maxWidth && height >= maxHeight;
scale = Math.min(width/maxWidth, height/maxHeight);
outer.style.transform = isMax?'':'scale(' + scale + ')';
wrapper.style.width = isMax?'':maxWidth * scale;
wrapper.style.height = isMax?'':maxHeight * scale;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
background: #e6e9f0;
margin: 10px 0;
}
#wrap {
position: relative;
width: 640px;
height: 480px;
margin: 0 auto;
}
#outer {
position: relative;
width: 640px;
height: 280px;
background: url('https://source.unsplash.com/random') no-repeat center center;
transform-origin: 0% 50%;
border-radius: 10px;
box-shadow: 0px 3px 25px rgba(0, 0, 0, 0.2);
overflow: hidden;
}
#outer:before {
content: "";
position: absolute;
bottom: 0;
width: 100%;
height: 100px;
-webkit-backdrop-filter: blur(20px);
backdrop-filter: blur(20px);
}
#profile {
background: url('https://source.unsplash.com/random/300x300') no-repeat center center;
position: absolute;
width: 60px;
height: 60px;
bottom: 0;
margin: 20px;
border-radius: 100px;
background-size: contain;
}
#content {
font-size: 20px;
position: absolute;
left: 0px;
bottom: 0;
margin: 30px 100px;
color: white;
text-shadow: 0 1px 2px rgba(0,0,0,0.5);
}
#content div:last-child {
font-size: 15px;
opacity: 0.7;
}
<div id="wrap">
<div id="outer">
<div id="profile"></div>
<div id="content">
<div>Monwell Partee</div>
<div>UX / UI Designer</div>
</div>
</div>
</div>
I took the answer from dc5, and put it in a small function that allows you to set the scale based on window.
function scaleBasedOnWindow(elm, scale=1, fit=false){
if(!fit){
elm.style.transform='scale('+scale/Math.min(elm.clientWidth/window.innerWidth,elm.clientHeight/window.innerHeight)+')';
}else{
elm.style.transform='scale('+scale/Math.max(elm.clientWidth/window.innerWidth,elm.clientHeight/window.innerHeight)+')';
}
}
if you want the element to fit, and not get cut off, just change Math.min
to Math.max
, or just set the fit parameter of this function to true.
Minified Version:
function scaleBasedOnWindow(elm,scale=1,fit){if(!fit){elm.style.transform='scale('+scale/Math.min(elm.clientWidth/window.innerWidth,elm.clientHeight/window.innerHeight)+')';}else{elm.style.transform='scale('+scale/Math.max(elm.clientWidth/window.innerWidth,elm.clientHeight/window.innerHeight)+')';}}