I'm trying to have a div
centered in the screen. This div should have a specific width
and height
when it fits in the available window space, but it should shrink to fit when the available window space is not enough, but also, maintaining its original aspect ratio.
I've been looking at lots of examples that work for a decreasing width
, but none that work for both width
and height
changes in the window size.
Here's my current CSS:
* {
border: 0;
padding: 0;
margin: 0;
}
.stage_wrapper {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background: gray;
}
.stage {
width: 960px;
height: 540px;
max-width: 90%;
max-height: 90%;
display: flex;
justify-content: center;
align-items: center;
background: chocolate;
object-fit: contain; /* I know this is for images, it's an example of what I'm looking for */
}
And, my current HTML:
<div class="stage_wrapper">
<div class="stage">
<p>Some text</p>
</div>
</div>
This is showing a centered div
that has a fixed width
of 960px and a fixed height
of 540px. It should never be bigger than that.
Then, if I change the size of my window to have a smaller width
or height
than that, the div
element is successfuly shrinking - except it is not maintaining the original aspect ratio, and that is what I'm looking for. I want it to respond to changes in both width
and height
.
Is this possible at all?
question from:
https://stackoverflow.com/questions/65864203/how-to-make-div-element-auto-resize-maintaining-aspect-ratio 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…