Reputation: 4762
Here is a JSFiddle. I applied the padding trick which works for horizontal resize. However, it doesn't work for vertical resize. In other words, I want the height of the yellow div to be a fixed percentage, say 15% of the container. But the aspect ratio of the yellow should stay fixed. So if I resize (downsize for instance) vertically, my goal is for the width of the yellow div to decrease as well as the height in order to: 1) maintain the aspect ratio. 2) maintain the percentage width and height of the yellow div. Is this possible without JavaScript? I'm fine with any CSS3 if available.
Below is the code as well:
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>
EDIT: Here is a fiddle of the desired behavior using jQuery. And here is the 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>
Upvotes: 0
Views: 203
Reputation: 15838
You can play with media queries and viewport dimentions. Something like:
// I used 15vw just as an example, you should do some maths and find the correct ratio/breakpoint
// this makes the box react to the horizontal resize
@media (min-width: 15vw) {
.content {
height: 12vw;
width: 28vw;
}
}
// now, at that breakpoint, the box size depends on the viewport's height
@media (max-height: 15vw) {
.content {
height: 80vh;
width: 185vh;
}
}
https://jsfiddle.net/f76p5nsr/
Personally, I would try to use vh and vw for all the dimentions of those blocks, this will help you do the math too.
Upvotes: 1