JSFiddle - React, Tailwind, and code Playground

by Nick Hulea

HTML

<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>

CSS

body,
html {
  margin: 0;
  padding: 0;
  background: #333;
}

#container {
  width: 100vw;
  height: 100vw;
  max-width: 1024px;
  margin: 0 auto;
}

#element_to_scale {
  width: 740px;
  height: 580px;
  background: #EEE;
  padding: 1em;
}

img {
  margin-right: 1em;
}

JavaScript

(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);

   (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);