Using CSS alone to maintain responsive aspect ratios: A solution to filling container heights

I'm trying to find a way for an inner div to fill the height of its container with a fixed aspect ratio of 1:1. The usual method using padding works great for filling the width, but not so much for the height.

Is it possible to achieve this purely with CSS and without using JavaScript?

It would be fantastic to have custom CSS units that are relative to the container's dimensions, similar to viewport units:

  • cw (container width)
  • ch (container height)
  • cmin (container min)
  • cmax (container max)

That would be amazing.

Check out an example code here

Answer №1

When it comes to setting the height in CSS, there is no direct equivalent of using padding-bottom for width.

One workaround I have used involves placing an img element with a data URL SVG (or a Base64 PNG) to avoid additional server requests and ensure a square size.

By setting the height of the image to 100%, it will maintain a square shape within its parent container, which has an inline block display. Using visibility: hidden can hide the image.

Check out the code snippet below:

.container {
  background-color: green;
  height: 50vh;
}

.fixed-aspect-ratio {
  display: inline-block;
  background-color: red;
  height: 100%;
  position: relative;
}

.fixed-aspect-ratio img {
  display: block;
  height: 100%;
  visibility: hidden;
}

.text {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
<div class="container">
  <div class="fixed-aspect-ratio">
    <img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><rect width='10' height='10'/></svg>">
    <div class="text">Some text</div>
    <!-- If you want text inside the container -->
  </div>
</div>

Answer №2

Adjust the height to 100% and set the width to x%

<!DOCTYPE html>
<html>

<head>
  <style>
    .container {
      background-color: green;
      height: 30vh;
    }
    
    .fixed-aspect-ratio {
      background-color: red;
      height: 100%;
      width: 10%;
      /* Maintain a 1:1 Aspect Ratio */
      position: relative;
      /* Position text inside it */
    }
    
    .text {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="fixed-aspect-ratio">
      <div class="text">Some text</div>
      <!-- Text inside the container -->
    </div>
  </div>
</body>

</html>

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

Can Django implement pagination without altering the URL structure?

I discovered the fundamentals of pagination in Django at this resource: Nevertheless, I am faced with a challenge - I wish to implement pagination without modifying the URL. Specifically, I need to paginate a single table among multiple tables on an HTML ...

Is it possible to connect a JavaScript file to an HTML document within a React application?

I have been developing a React website with the following file structure: public: index.html second.html src: index.js second.js table.js forms.js The main page (index.js) contains both a form and a table. One of the columns in the table has a link t ...

Steps to Display a JavaScript Function Two Times on a Single Page

Hey there! I'm currently working on a project where I need to display the output of my function in two separate divs. However, when I try to simply output the same ID, it messes up the whole code and the output becomes null. Here's the code snipp ...

The drop-down menu seems to have disappeared from sight

I'm having an issue with getting a dropdown to appear in my registration form. Everything else in the form is displaying correctly and functioning properly, but the dropdown remains invisible. After searching extensively, I haven't been able to ...

Dealing with HTML fitting issues on screen dimensions

I'm currently working on a unique application that focuses on tracking and storing running/cycling routes through the integration of OSM/Google Maps. My goal is to have the application function seamlessly without any need for page scrolling, ensuring ...

Notify the user immediately if an HTML template is stolen using Jquery and PHP

After uploading an HTML template to themeforest, I discovered that some websites were giving away the full source code for free. Since HTML is easy to copy, obfuscation doesn't solve the issue. Is there a way to use JQuery to alert me if someone hosts ...

Using DataTable with backend processing

Has anyone successfully implemented pagination in DataTable to dynamically generate the lengthMenu (Showing 1 to 10 of 57 entries) and only load data when the next page is clicked? I'm currently facing this challenge and would appreciate some guidance ...

Would you like to learn how to set an auto-play video as the background in a webpage section, similar to the one found on http://www8.hp.com/in/en/home.html?

I was browsing the HP-India website and noticed they have a cool autoplay video in the background of a section below the header. I would love to recreate something similar on my own website. Any tips on how to achieve this? ...

What is the best way to eliminate HTML unicode content from the final item in a continuously changing list?

li:after{ content:"\00b6"; } <ol> <li>banana</li> <li>orange</li> <li class="last-class">apple</li> </ol> I am currently working on a dynamic list where the number of <li> tags varies over t ...

Pressing the button will add text into the input field

Below is a jsfiddle link showcasing the current issue I am trying to address: http://jsfiddle.net/YD6PL/61/ Here is the HTML code snippet: <input type="text> <input type="text> <input type="text> <div> <button class="buttons"& ...

The Bootstrap 4 Toggler Dropdown lacks a background color

Struggling to style the toggle dropdown on smaller screens to match the regular navbar background? Can't seem to figure out how to target it. Is there a missing bootstrap class or an error in the code? Initially suspected the border might be causing i ...

Switch your attention to the following input text using AngularJS

In my controller, I have an object variable called `myObject` with 3 input text fields in the user interface. I am looking for a way to automatically shift the focus to the next input field once the current one reaches its maximum length. var myObject = ...

Is there a solution to fix the issue with IE causing hover effects not to

I'm currently in the process of designing a website, and I have implemented some image hover effects that reveal elements within the image when you hover over it. These effects are functioning correctly on Chrome, Safari, and Firefox; however, they ar ...

Crafty Checkbox Selector [ leveraging jquery ]

I have created some fake checkboxes using elements like <span> after the real checkbox and they are working fine! However, I am having trouble counting the checked checkboxes when a checkbox is clicked. I have tried using methods like: $(".elm:chec ...

Having trouble locating an element on a webpage? When inspecting the element, are you noticing that the HTML code differs from the source page?

I'm having trouble locating a specific element on a webpage. When I use the Inspect Element tool, I can see the HTML code with the element id = username, but when I check the page source, all I see is JavaScript code. Does anyone have any suggestions ...

Modifying CSS using jQuery in a PHP While Loop

I've been racking my brain trying to solve this issue, experimenting with different approaches but so far, no luck. Question: How can I dynamically change the color of a specific div within a PHP while loop using jQuery after receiving an AJAX respon ...

Tips for creating a dynamic animation: How to make a div fall from the top and rotate

Hey everyone, I'm working on creating an animation where a phone falls from the top and then rotates and skews to give the illusion of a 3D shape when it reaches the bottom. However, I'm facing an issue with flickering in the animation when it hi ...

Display text when hovered over or clicked to insert into an HTML table

I have an HTML table connected with a component field gameArray and I need it to: Show 'H' when the user's cursor hovers over TD (:hover) and the corresponding field in gameArray is an empty string, Fill the gameArray field after a click. ...

Fluctuating problem arises when placing one div over another div while hovering

Sorry if the title isn't clear. Basically, I have a div that when hovered over, triggers another div to appear with display:block, showing it above the original div. It works well but there is some flickering when moving the cursor over the second div ...

Is it possible to alter the color of an icon image using CSS?

I'm currently exploring ways to modify the color of an image that has a transparent and solid color split. My goal is to change the white portion for hover effects, and create a dynamic way to alter colors within WordPress without relying on Photosho ...