Preserve the aspect ratio of a div even when the height changes dynamically

I was intrigued by the idea of creating a square div using only CSS, where its height adjusts dynamically and its width scales based on that height.

In the snippet below, you can see that the container's height adapts based on its content. The red square within the container should take up the entire height and have a width equal to that height.
While I know how to maintain aspect ratio of a div based on its width, I couldn't find a solution for dynamic height scenarios.

Any assistance on this matter would be greatly appreciated! Thank you so much!

Please note: Since the height is dynamic, solutions involving 'vh' did not work, and the snippet provided is just for experimentation.

#container {
  width: 400px;
  padding: 20px;
  border: solid 1px black;
  position: relative; 
}

.square {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0; 
  background-color: red;
  
  width: 100px /*This is just a placeholder value*/
}
<div id="container">
  <div class="content">
    This is a dynamic content
  </div>
  <div class="square"></div>
</div>

Answer №1

Consider this alternate solution:

To achieve the desired effect, we can create a nested div within the primary .square div that inherits the height of its parent.

By rotating the inner div, its height will now become its width. To finalize the layout, simply hide the overflow from the parent div and apply some translation to ensure proper positioning.

#container {
  width: 400px;
  padding: 20px;
  border: solid 1px black;
  position: relative;
}

.square {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
  pointer-events: none;
}

.square>div {
  background-color: red;
  transform: rotate(-90deg) translate(100%, 0%);
  width: 100vw;
  height: 100%;
  transform-origin: 100% 100%;
}
<div id="container">
  <div class="content">
    <textarea> I'm a dynamic content</textarea>
  </div>
  <div class="square">
    <div></div>
  </div>
</div>

Answer №2

Here is the solution:

Please take note that I have included the contenteditable attribute to the content div, allowing you to input text in the snippet to observe its effect. This step may not be required in your particular version.

#container {
  width: 400px;
  padding: 20px;
  border: solid 1px black;
  position: relative; 
}

.square {
  position: absolute; z-index:-1;
  left:0;
  top: 0;
  right: 0;
  bottom: 0; 
  background-image:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsIAAA7CARUoSoAAAAANSURBVBhXY/jPwPAfAAUAAf+mXJtdAAAAAElFTkSuQmCC');
  background-size:contain; background-position:100% 0;
  background-repeat:no-repeat;
}
<div id="container">
  <div class="content" contenteditable="true">
    I'm a dynamic content
  </div>
  <div class="square"></div>
</div>

The technique employed here involves using a red square (essentially a 1×1 image) as the background which is proportionately sized with the contain property. Unfortunately, achieving this effect with just the background-color attribute is not feasible.

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

Looking for a way to add a CSS effect that reveals another image or text when hovering over an image?

My company's website features 10 country flags that, when clicked, display the entire site in that country's language for the user's session. However, I want to take it a step further and have a small image of the respective country appear w ...

The appearance of a printed webpage does not match what is shown in Google Chrome's Print Preview feature

I have encountered a strange issue that has me stumped. I need the webpage in my current project to be completely printable, but I'm facing difficulties. While the signature field and note field (with the text "erererer") display perfectly in Google C ...

Step-by-step guide on integrating node.js and MySQL to store data from an online form in a database

Currently, I am attempting to insert data into a MySQL database using node.js by clicking the submit button. However, an error message has appeared and despite understanding it somewhat, I am unsure of how to proceed. Any assistance would be greatly apprec ...

Calculate the total sum of input values using jQuery

Here is the HTML I've been working with: I am trying to create a script where one textbox will display the total amount, and another textbox will display the following data: "name": [{ "id": 3, "qty": 2 }, { "id": 4, "qty": 5 }] Here's ...

Is it possible to alter the style of the <input type="file"> element?

After attempting to modify the HTML form input type file, here is the snippet of code I used: In HTML, within form id = form <input class="upload_file" type="file" id="file" name="file" /> .CSS I experimented with both approaches: .upload_button{ ...

Receiving a NaN output rather than a numerical value

Experiencing what seems to be a straightforward syntax error, but I'm unable to pinpoint it. Controller: $scope.startCounter = 3; $scope.startTimeouter = function (number) { $scope.startCounter = number - 1; mytimeouter = $t ...

Is it possible to deactivate an anchor tag based on the result of a conditional statement that returns a string?

I've created an anchor tag (not a button) with text that redirects me to another page <StyledTableCell align="center"> <Link href={`/races/results/${race.id}`}>{race.race_name}</Link> </StyledTableCell> There is a ...

Issues with Mouse Hover/Image Replacement

In this particular example, I am attempting to achieve a simple functionality where an image changes when the mouse hovers over it, and reverts back to the original image when the mouse is no longer hovering. However, despite my efforts, there seems to be ...

The issue of changing the body font size in MUI v5 with React Styleguidist, ScopedCSSBaseline, and createTheme style overrides remains unresolved

Recently, I successfully migrated two MUI-powered UIs from MUI v4 to v5. In the process, I had to override their body fontSize according to the MUI migration guide to maintain the v4 design default of Typography body2 font size. This adjustment has worked ...

What is the best way to set the screen height without needing to scroll vertically?

How can I make the orange and blue area extend to the end of the screen or have the full screen size minus the height of the navbar? When using `vh-100`, it fills the full height but creates a vertical scrollbar which is not desired. Is there a way in Boot ...

How can I locate the first word using XPath?

When dealing with the following HTML / XML code: <div class="contentBlock"> <h2> </h2> <h1></h1> <h1>DBS055 - single module packages</h1> </div> I am interested in extracting only the code D ...

Tips for displaying images dynamically in HTML using AngularJS

src={{logo}} var logo = 'localhost:3000/modules/images/default.png' I'm trying to display the image path dynamically, but it's not showing up in the HTML. Do I need to use quotes for src? Can someone please assist me with this issue? ...

How to switch between classes for elements and return to the original one when none of the elements is chosen

Hello there, I need some assistance. Here's the scenario: I am working with a grid of six items. My goal is to have the first item in the grid become active by default. When the user hovers over any of the remaining five items, I want the active clas ...

Angular framework does not trigger the button click event

Currently, I am in the process of creating a web app and working on designing the register page. My experience with Angular is still at a beginner level. The following code snippet is from the resiger.component.ts file: /** * To create a new User ...

I am interested in utilizing Google Apps Script (GAS) to store images in GoogleDrive and automatically populate the corresponding URL in a

Currently, I am utilizing GoogleAppsScript to develop a form for submitting names and images. The idea is to store the submitted name and image in GoogleSpreadSheet while also storing the image in GoogleDrive along with its destination URL. The process inv ...

WordPress having trouble rendering the stylesheet code

I am facing an issue with Wordpress where my CSS file is not loading properly. The stylesheet contains a rule to center the header image, but for some reason it's not working. I've also tried adding a margin-left of 100px, but that doesn't s ...

Creating a Kendo Grid that mimics the appearance and functionality of an

Can someone help me with styling my Kendo grid to match the look of a basic HTML table? I want to use the table style I already have set up instead of the default Kendo style. Is there a way to achieve this? #resultTable th { cursor:pointer; } #result ...

Sorting across several lists leads back to the initial list

I currently have multiple lists, with each list and item sharing the same class. For example: <ul class="cat_1"> <li class="cat_1">Item1</li> <li class="cat_1">Item2</li> <li class="cat_1">Item2</li> ...

Implementing a Slide animation in React

I am currently working on a carousel feature that includes two buttons, Next and Previous. When the user clicks on Next, I want the carousel to slide from left to right, and when they click on Previous, it should slide from right to left. One important not ...

Utilize VBA in Excel to interact with a jQuery button on a web page

Can anyone provide assistance with my VBA Excel code issue? Set ieDoc = Nothing Set ieDoc = ieApp.Document For Each Anchor In ieDoc.getElementsByTagName("div") If InStr(Anchor.outerHTML, "CategoryIDName-popup") > 0 Then ...