Skip to content

Instantly share code, notes, and snippets.

@Jae-kwang
Forked from lyudmil-mitev/index.html
Last active June 3, 2022 08:56
Show Gist options
  • Save Jae-kwang/303d6870b5ec314784dfa765cbab7b34 to your computer and use it in GitHub Desktop.
Save Jae-kwang/303d6870b5ec314784dfa765cbab7b34 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"
/>
<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) {
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
);
}
const getXPosition = (el) => {
const parentWidth = el.parentElement.clientWidth;
const { width: childWidth } = el.getBoundingClientRect();
return parentWidth / 2 - childWidth / 2;
};
function fitToParent(element, margin) {
// 확대 비율 계산
const scale = scaleAmountNeededToFit(element, margin);
// 확대 비율 적용
element.style.transformOrigin = "0 0";
element.style.transform = `scale(${scale})`;
// 확대 적용 후 변경된 element 기준 X position 계산
const xPos = getXPosition(element, margin);
// X Position 반영
element.style.transform = `translate(${xPos}px, 10px) scale(${scale})`;
}
global.fitToParent = fitToParent;
})(this);
body,
html {
margin: 0;
padding: 0;
background: #333;
}
#container {
width: 800px;
height: 800px;
background-color: green;
}
#element_to_scale {
width: 500px;
height: 900px;
background: #EEE;
padding: 1em;
}
img {
margin-right: 1em;
width: 100%;
}
@Jae-kwang
Copy link
Author

스크린샷 2022-06-03 오후 5 51 04

  • element_to_scale 의 width, height 를 조절함에 따라 확인 가능

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment