Flexible container with consistent aspect ratio for its dynamic content

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>

Answer №1

If you want to create responsive boxes, consider using media queries along with viewport dimensions. Here is an example:

// The values used here are just examples, adjust them based on your needs
// This CSS code will make the box resize according to the width of the viewport
@media (min-width: 20vw) { 
  .box {
    height: 10vw;
    width: 25vw;
  }
}

// When the viewport height reaches a certain size, the box dimensions will change accordingly
@media (max-height: 15vh) {
  .box {
    height: 70vh;
    width: 150vh;
  }
}

Check out this example on JSFiddle for reference.

In general, using vh and vw units for sizing elements can simplify the calculation process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery to toggle an open and close button

My icon functions as an open/close button. When opened, it turns red and rotates 45 degrees. The issue arises when trying to close it. Changing the div class causes the icon to disappear while in its active state. Below is the jQuery code I am using: $(". ...

Adjust remaining vertical space

Trying to design a TailwindCss layout that resembles the following: +----------------------+ | | +-----+----------------+ | | | | | | | | | | | | +-----+------ ...

Using CSS and Vue, you can customize the appearance of inactive thumbnails by displaying them

My goal is for a clicked thumbnail to display in color while the others show as grey. The active thumbnail will be in color, and I want inactive thumbnails to appear in grey. Here is what I am trying to achieve: Vue.component('carousel', { ...

Display a section of the picture at maximum width

Can anyone help with displaying only a portion of an image at full width (100%) without any overflow issues? The code I've tried is not working: .intro_sea { position: absolute; width: 101%; clip-path: inset(30% 50% 0 0); margin: 0; paddi ...

The system encountered an error stating that the class 'Database' could not be found

Whenever I try to establish a connection to my SQL database using my pdo_object.php file, I encounter the following error in my model.php: Fatal error: Class 'Db' not found in /path/model.php on line 8 I have double-checked that all permissions ...

Improper headings can prevent Chrome from continuously playing HTML5 audio

Recently, I encountered a peculiar and unlikely issue. I created a custom python server using SimpleHTTPServer, where I had to set my own headers. This server was used to serve .wav files, but I faced an unusual problem. While the files would play in an ...

Tips for linking a sub-item in a tree-view diagram using CSS

I am looking to create a visually appealing list of items and sub-items that are connected with lines. Currently, I have implemented the following CSS code - ul { list-style: none; } ul.sub-menu { position: relative; padding: 0; margin-left: ...

Live CSS editing tool

Are there any Javascript libraries or plugins available that enable real-time modification of CSS classes/styles on a webpage? ...

What is the best way to position this material-ui select list at the bottom of the input block for proper alignment?

My material-ui select build is working fine overall, but I'm looking to align the top line of the select list with the bottom line of the input block. Any ideas on how to achieve this? This is my code: const styles = theme => ({ formControl: { ...

Struggling to understand how to transfer data between two PHP files

I've been trying to send an array through POST and two variables through GET from first.php to second.php file, but I'm encountering an issue where I keep getting the error message Undefined index first.php <?php session_start(); $_S ...

moving a simulated element to a new location

Looking for some help with my html/CSS code that creates a unique element at the bottom of a div with an image background. The shape I've created is positioned at the bottom of the div... Below is the HTML: <div style="background-image:url(&apos ...

The label and its .input-group in Bootstrap 5 are not aligned on the same line

<div class="input-group mb-3"> <label class="input-group-text form-floating ">Please Share Your Name *</label> <input type="text" class="form-control" placeholder="First Name&quo ...

Is there a way to extend the styles applied to elements after the page has finished loading?

I have created an application with a element positioned at the top of the page. Directly below this element is another div. Upon clicking a button within the first element, HTML content from a website is loaded into the second div, bringing along all its ...

The slicing of jQuery parent elements

Hey there! I recently created a simulated "Load More" feature for certain elements within divs. However, I've encountered an issue where clicking on the Load More button causes all elements in both my first and second containers to load simultaneously ...

Having trouble with JavaScript in a project I'm trying to replicate

For my coding practice, I am working on a project where clicking on the images should change the main product displayed along with its color. However, nothing happens when I click on the products. Can anyone point out what I might be doing wrong? Here is ...

Setting button height dynamically in React Native

I've implemented a button using React Native Elements in my layout. Here's the code snippet: <Button title="Login" buttonStyle={{ backgroundColor: Colour.green }} containerStyle={{ ...

The foreach loop is failing to execute the code

Below is the code snippet I am working with: var divarray = document.getElementById("yui-main").getElementsByTagName("div"); var articleHTML; var absHTML; var keyHTML; var bodyHTML = []; for( var i in divarray) { if(divarray[i].className == "articleB ...

Are HTML APIs included in the HTML5 standard specifications?

While studying HTML5 on W3Schools, I stumbled upon a section dedicated to HTML APIs. These APIs cover functionalities like geolocation and drag/drop on webpages. You can find an example here. The code provided is written in JavaScript and included within ...

Android not displaying images in React Native

When working with React Native for Android, I have utilized hdpi, mdpi, xhdpi, xxhdpi, and xxxhdpi in the assets folder. However, I've encountered a problem where some images display correctly while others get resized unexpectedly (changing in size) ...

Encountering an issue while trying to incorporate a Language Selector on my website

I've been working on a website that offers English and Macedonian language options. However, I'm facing an issue where switching to the Macedonian version of the site changes the language displayed but the selector still shows "EN." This prevents ...