JSFiddle - React, Tailwind, and code Playground

by braveminds1823

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

#element_to_scale {
  width: 640px;
  height: 480px;
  background: #EEE;
  padding: 1em;
  resize: both;
}

img {resize: both;
  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);