`object-fit: contain` for divs

by Scott Shepherd

HTML

<div id="container" class="resizable">
<div id="object"> 
  <p>
    Resize my container<br/>
    I stay 16:9
  </p>
</div>
</div>

CSS

#container {
  background: lightgray;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 200px;
  height: 200px;
}

#object {
  background: pink;
  aspect-ratio: 16/9;
  overflow: hidden;
}

.resizable {
  resize: both;
  overflow: auto;
}

p {
  margin: 0.5em 0.75em;
  font-family: Georgia, serif;
}

JavaScript

const container = document.getElementById('container');
const object = document.getElementById('object');
const aspectRatio = 16/9;

function update() {
	const isTall = container.clientWidth / container.clientHeight < aspectRatio;
	object.style.width = isTall ? '100%' : 'auto';
  object.style.height = isTall ? 'auto' : '100%';
}

new ResizeObserver(update).observe(container);