Check out this JSFiddle where I implemented the padding trick to maintain the aspect ratio of a yellow div. While it works for horizontal resize, it doesn't quite cut it for vertical resizing. My goal is to have the height of the yellow div fixed at a certain percentage, like 15% of its container, while also preserving the aspect ratio. So when I resize vertically, the width and height of the yellow div should decrease proportionally to maintain both the aspect ratio and the set percentage dimensions. Is there a CSS-only solution for this or would I need JavaScript? Any CSS3 tricks would be appreciated.
Here's the code snippet:
html, body {
height: 100%;
}
.container {
position: relative;
left: 10%;
width: 80%;
height: 80%;
top: 10%;
background-color: maroon;
}
.content {
background-color: yellow;
width: 20%;
padding-top: 10%;
bottom: 0;
position: absolute;
left: 40%;
/* height: 15%; of course this doesn't work */
}
<div class="container">
<div class="content">
</div>
</div>
UPDATE: For the desired behavior achieved using jQuery, you can check out this JSFiddle link. Here's the accompanying code:
$(window).resize(function () {
$(".content").height($(".container").height() / 5);
$(".content").width($(".container").width() / 5);
if ($(".content").width() / $(".content").height() < 3) {
$(".content").height($(".content").width() / 3);
}
else {
$(".content").width($(".content").height() * 3);
}
$(".content").css("left", ($(".container").width() - $(".content").width()) / 2);
}).resize();
html, body {
height: 100%;
}
.container {
position: relative;
left: 10%;
width: 80%;
height: 80%;
top: 10%;
background-color: maroon;
}
.content {
background-color: yellow;
bottom: 0;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="content">
</div>
</div>