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

Finding the element and extracting its text value

Below is the HTML code: <span> <b>Order number:</b> </span> <span>A36HASJH</span> The value within the span element, A36HASJH, is dynamic and changes with each order. How can I identify this element and store it as a s ...

Changing the Image Source in HTML with the Power of Angular2

Despite my efforts, I'm unable to display the updated image in my HTML file. In my TypeScript file, the imageUrl is updating as expected and I've verified this in the console. However, the HTML file is not reflecting these changes. In my researc ...

Steps on how to trigger an onmouseover event for entire blocks of text:

I'm currently in search of an onmouseover code that seems to be elusive on the vast internet. A CSS box format has been successfully created: .box { float: left; width: 740px; height: 300px; margin-left: 10px; margin-top: 10px; padding: 5px; border: ...

Having an iframe at the bottom of the page is causing unnecessary white space below the

I currently have an iframe placed in the footer of my website. When I try to set the height of the iframe to match the height of the footer, it results in unwanted white space appearing below the iframe. The issue can be seen here: JSFiddle To fix this p ...

What is the correct way to utilize ng-if/ng-show/ng-hide to hide or show HTML elements within the app.run function

I am currently working on developing an app that loads views correctly. HTML: <body> <loading outerWidth='1000' outerHeight='1000' display='isReady'></loading> <div class='wrapper' ng-sho ...

Show two <p>'s next to each other

I am trying to arrange 2 paragraphs side by side. <p class = "firstClass">This is the first paragraph.</p> <p class = "secondClass">This is the second paragraph.</p> Result: This is the first paragraph. This is the second paragra ...

Storing HTML elements in a database using jQuery's html() method

I have encountered a dilemma that has left me stumped after extensive online research. I have a dynamically generated webpage and need to save the entire appended body of the page to a database using PHP and MySQL. My current approach involves using the fo ...

The width of DIVs in Mac Safari exceeds that of other browsers

Encountering an issue that is specific to MAC Safari. Here's the code snippet: <div class="wrapper" style="max-width:1220px"> <div style="width:50%;display:inline-block">First</div> <div style="width:25%;display:inline-block"&g ...

Troubleshooting JavaScript for Sidebar Disappearance due to marginRight and display CSS Issue

I need to adjust the layout of my website so that the sidebar disappears when the window is resized below a certain width, and then reappears when the window is expanded. Here is the HTML code: <style type="text/css"> #sidebar{ width:290 ...

Issue with .submit() not submitting form after setTimeout timer runs out

How can I add a delay after a user clicks submit on a form before it actually submits? I have an image that appears when the click event is triggered, but the form never actually submits... This is the HTML form in question: <form class='loginFor ...

CSS Trick: Applying first-of-type selector to specific instances of a div

I'm currently grappling with how to specify that a 'first-of-type' should only be present on specific instances of a div. For instance, suppose I have a class called ".maintext" and in some cases I want the first paragraph to feature a dropc ...

Why does the <div> element still have an offset even though its width and height are set to 100px and padding, margin, and border are set to 0px?

After styling my div element with specific CSS rules, I'm encountering an issue. The div has a set width and height of 100px along with padding, border, and margin all set to 0px. However, the elements are not being offset from the edges of the browse ...

Can you guide me on implementing CSS Houdini in Next.js?

Exploring the world of CSS Houdini in my Next.js project has been quite an adventure. After successfully installing the necessary CSS Houdini package and css-paint-polyfill using yarn, I decided to follow the webpack guidelines provided at . Below is a sn ...

Despite locating the button, Protractor still encounters difficulties when attempting to click on it

I've been having trouble clicking on a button using Protractor. The issue is that even though the driver can locate the element, it still won't click on it. Any assistance would be greatly appreciated. Thank you in advance. Here is the HTML for ...

Incorporate negative padding in order to smoothly scroll to a specific ID

When I jump to an ID using domain.com/#section, the scroll goes too far down and needs a negative margin added. Is there a way to achieve this directly in the URL without relying on CSS, jQuery, or JavaScript? ...

Update the HTML weather icon with data from JSON

I have a collection of weather icons stored on my computer. How can I customize the default weather icons with my own set of icons? In the JSON file, there is a variable like this: "icon":"partlycloudy" <html> <head> <script src="http://c ...

Tips on creating a responsive div element within the viewport?

I have a variety of nested div elements within a parent div, set up like this: #mycontent > div { width: 14.28%; } <div id="myheader">some header content</div> <div class="container" id="mycontent"> <div class="outerdiv" id= ...

Adding a hyperlink to each table cell (td) in HTML and CSS that is visible outside of the table

In my table, there is a link on every td. I want these links to appear outside the table. Although I have achieved this, the first cell that was created needs to be hidden. When I try to hide the td using CSS, the link also disappears. Here is the HTML: ...

Fetch HTML content from a local file using Vue

I am currently searching for a method to import HTML content from a file located at /src/activities/0/2/content.html The specific numbers in the path are interchangeable variables. My goal is to achieve something along the lines of mounted(){ this ...

Changing the content of a form with a personalized message

I am currently working on a Feedback modal that includes a simple form with fields for Name, rating, and comment. After the user submits the form, I intend to display a custom message such as "Your feedback has been submitted." However, I am facing an issu ...