JSFiddle - React, Tailwind, and code Playground

HTML

<div id="wrapper"><div id="content"></div></div>

CSS

#wrapper {
  display: inline-block;
  padding: 10px;
  background-color: green;
}

#content {
  background-color: red;
}

JavaScript

class AutoBoundsTransition {
  static for(node) {
    if (!this._context) this._context = new WeakMap();
    if (!this._context.has(node)) this._context.set(node, new this(node));
    
    return this._context.get(node);
  }
  
  pRequestAnimationFrame() {
    return new Promise(resolve => requestAnimationFrame(resolve));
  }
  
  constructor(node) {
    this.node = node;
  }
  
  lockBounds() {
    this.lockedWidth = this.node.getBoundingClientRect().width;
    this.lockedHeight = this.node.getBoundingClientRect().height;
    
    this.oldHeight = this.node.style.height;
    this.oldWidth = this.node.style.width;
    
    this.node.style.width = this.lockedWidth + `px`;
    this.node.style.height = this.lockedHeight + `px`;
  }
  
  waitTransitionFinish() {
    let resolve = null;
    let promise = new Promise(res => resolve = res);
    
    this.node.addEventListener(`transitionend`, function listener(event) {
      event.target.removeEventListener(`transitionend`, listener, true);
      resolve();
    }, true);
    return promise;
  }
  
  async fitContent(duration) {
    let oldTransition = this.node.style.transition;
    this.node.style.height = this.oldHeight;
    this.node.style.width = this.oldWidth;
    
    await this.pRequestAnimationFrame();
    let newWidth = this.node.getBoundingClientRect().width;
    let newHeight = this.node.getBoundingClientRect().height;
    
    this.node.style.width = this.lockedWidth + `px`;
    this.node.style.height = this.lockedHeight + `px`;
    
    await this.pRequestAnimationFrame();
    this.node.style.transition = `height ${duration}ms, width ${duration}ms`;
    this.node.style.height = newHeight + `px`;
    this.node.style.width = newWidth + `px`;
    
    await this.waitTransitionFinish();
    this.node.style.transition = null;
    this.node.style.height = this.oldHeight;
    this.node.style.width = this.oldWidth;
  }
}

class AutoBoundsWrapper {
  constructor(node, duration=500) {
    this.autoBoundsTransition =...