The snippet posted below is very close to my desired behavior: having a div in the center of the screen maintain its aspect ratio to the maximum size possible while being centered in its parent div. However, when the width of the screen is too small, the div is not centered, it is aligned to the top. When the width is large enough, the margin: auto
trick works as expected and centers the div accordingly.
<html>
<head>
<style>
html, body {
margin: 0;
color: white;
}
html, body, #root { height: 100%; }
#top, #bottom { margin: 1em; }
#root {
background-color: black;
display: flex;
flex-direction: column;
}
#middle {
flex: 1;
background-color: grey;
overflow: hidden;
}
#box {
margin: auto;
aspect-ratio: 4/3;
border: 3px solid red;
max-width: calc(100% - 6px);
max-height: calc(100% - 6px);
}
</style>
</head>
<body>
<div id="root">
<div id="top">Top panel</div>
<div id="middle">
<div id="box"></div>
</div>
<div id="bottom">Bottom panel</div>
</div>
</body>
</html>
The closest solution I found to perform what I am looking for is here: https://codepen.io/wattenberger/pen/vYOOPXv. However, this works purely off view width and height. Completely ignoring the constraint of top or bottom panels like I require.
CodePudding user response:
Just add it to your #box
.
position: relative;
top: 50%;
transform: translateY(-50%);
CodePudding user response:
Remove the margins. In your flex container, give "align-items: center;" a try and lemme know if that worked.