I have an outer container that is variable in size and width. Suppose that inside this container, I have a canvas that I want to have grow as much as it can while maintaining proportion and not cropping. For this, I would normally use object-fit: contain
.
Now, suppose instead of just a canvas, I have a canvas with another element placed next to it.
HTML:
<div class="outerContainer">
<canvas width="640" height="360"></canvas>
<div class="beside">
</div>
</div>
CSS:
.outerContainer {
display: flex;
border: 0.5em solid #444;
margin-bottom: 2em;
object-fit: contain;
}
.outerContainer canvas {
flex-grow: 1;
background: #77a;
}
/* This element has a fixed width, and should be whatever height the <canvas> is */
.outerContainer .beside {
flex-basis: 3em;
flex-grow: 0;
flex-shrink: 0;
background: #7a7;
}
In this case, I want to scale the whole outerContainer size, just like I did with canvas. The problem is that object-fit
doesn't actually scale the element... it scales its contents. This doesn't seem to apply to normal block elements, resulting in a case where the canvas inside is potentially skewed if there is enough width.
If I add object-fit: contain
to the canvas
element, it maintains proportion but still uses the full width, meaning the .beside
element is all the way to the right. This is visualized with the purple background on the canvas.
What I would like is the outerContainer
to be scaled with the canvas contents, so that .beside
always has the height of the canvas contents. The .outerContainer
should be centered in the parent element, taking up as much space as it can without distorting the canvas. Like this, at any proportional scale:
Is this doable with modern CSS? Or must I use a scripted solution?
Fiddle with examples: https://jsfiddle.net/nufx10zc/