Skip to content

Instantly share code, notes, and snippets.

@Eskuero
Forked from lyudmil-mitev/index.html
Created August 10, 2021 18:10
Show Gist options
  • Save Eskuero/79cd5b8b66e37826ddd67b8d51569a78 to your computer and use it in GitHub Desktop.
Save Eskuero/79cd5b8b66e37826ddd67b8d51569a78 to your computer and use it in GitHub Desktop.
CSS Transform Scale element to fit its parent
<html>
<head>
<title>CSS Transform Scale element to fit its parent</title>
<script src="scale2fit.js"></script>
<link rel="stylesheet" href="style.css"/>
<script>
(function(window) {
function main() {
const margin = 10;
requestAnimationFrame(function fitToParentOnResize() {
fitToParent(document.getElementById('element_to_scale'), margin);
});
}
window.addEventListener("DOMContentLoaded", main);
window.addEventListener("resize", main);
})(this);
</script>
</head>
<body>
<div id="container">
<div id="element_to_scale">
<h1>Lorem Ipsum</h1>
<img src="https://upload.wikimedia.org/wikipedia/en/5/5f/Original_Doge_meme.jpg" alt="doge" align="left" />
<h4>"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."</h4>
<h5>"There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain..."</h5>
</div>
</div>
</body>
</html>
(function(global) {
/*
Simple functions to scale content to fit it's parent
Author: Liudmil Mitev
License: WTFPL
Demo: https://jsfiddle.net/oxzxyxqn/7/
*/
function scaleAmountNeededToFit(el, margin = 0) {
const parentSize = {
width: el.parentElement.clientWidth - margin * 2,
height: el.parentElement.clientHeight - margin * 2
};
return Math.min(parentSize.width / el.clientWidth,
parentSize.height / el.clientHeight);
}
function fitToParent(element, margin) {
const scale = scaleAmountNeededToFit(element, margin);
element.style.transformOrigin = "0 0";
element.style.transform = `translate(${margin}px, ${margin}px) scale(${scale})`;
}
global.fitToParent = fitToParent;
})(this);
body,
html {
margin: 0;
padding: 0;
background: #333;
}
#container {
width: 100vw;
height: 100vw;
}
#element_to_scale {
width: 640px;
height: 480px;
background: #EEE;
padding: 1em;
}
img {
margin-right: 1em;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment