I can find multiple half solutions, but I am looking for a complete solution to my issue. I have a div that I would like to be centered in the screen with a fixed aspect ratio, that div should in essence always be completely visible, so that div is always the largest it can be whilst keeping the aspect ratio. regardless of resizing the window vertically and horizontally.
There is a codepen here: https://codepen.io/william-bang/pen/ZjyWRd
That I created, this only solves the issue horizontally but not vertically. I have managed to get it working with and but sizing behaves differently for that. I am looking for a CSS solution, although I am open to a JS solution, if anyone is absolutely sure that no solution exists.
body {
width: 100%;
height: 100%;
}
.wrapper {
width: 40%;
height: 100%;
margin: auto
}
.img {
padding-top: 50%;
width: 100%;
background: #ccc;
text-align: center;
}
<div class="wrapper">
<div class="img">
**IMG HERE**
</div>
</div>
I would be grateful for any suggestions, this has had me stumped for many hours. thanks in advance :)
Update, the div needs to maintain its aspect ratio on a varying page and at all times be its own maximum size.
@Grenther Thanks for your response, I tried modifying the answer you gave to do it purely in CSS and not having to use a CSS preprocessor. That went really well, until I realized that CSS media queries does not support standard CSS variables, otherwise the method you proposed would have been possible without SCSS but perhaps you already knew that.
:root {
--ogW: 1600;
--ogH: 900;
--ratio: calc( var(--ogW) / var(--ogH));
}
body {
width: 100%;
height: 100%;
}
.ratio {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
@media screen and (max-width: 177vh) {
width: 90vw;
height: calc( 90vw / var(--ratio));
}
@media screen and (min-width: 177vh) {
width: calc( 90vh * var(--ratio));
height: 90vh;
}
}
.div {
width: 100%;
height: 100%;
background: red;
text-align: center;
}
<div class="ratio">
<div class="div">
Hello!
</div>
</div>