Maintaining a child div with an aspect ratio of 16/9 to always fit within a parent div using CSS is proving to be a challenge

I am currently facing a challenge in adding a face overlay to an image while ensuring that the face remains within the inner div.

The image is required to fit over a 16/9 ratio backdrop and also stay within the outer container. I have managed to achieve this when the outer div has a greater height than the 16/9 ratio, but the issue arises when it drops below 16/9 as it cuts off the top and bottom of the head.

This needs to be functional on IOS where aspect-ratio does not work on Safari, leading me to resort to using the padding-top solution for 16/9.

If anyone can provide assistance or guidance, it would be greatly appreciated.

My desired outcome looks something like this...

https://i.sstatic.net/vvc9g.png

However, what I'm currently experiencing is this...

https://i.sstatic.net/FysoW.png

.outside {
  position: relative;
  width: 500px;
  height: 200px;
  background: red;
    overflow: hidden;
}

.inside {
  height: 0;
  overflow: hidden;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding-top: 56.25%;
  background: blue;
}

.img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: contain;
}
<h1>Works when height is bigger</h1>

  <div class="outside" style="height:400px!important">
  <div class="inside" style="padding-top: 56.25%;">
    <img src="https://solvemoji-test.s3.eu-west-2.amazonaws.com/unnamed.jpg" class="img">
  </div>
</div>

<h1>Does not work when height is smaller</h1>

<div class="outside">
  <div class="inside" style="padding-top: 56.25%;">
    <img src="https://solvemoji-test.s3.eu-west-2.amazonaws.com/unnamed.jpg" class="img">
  </div>
</div>

Answer №1

When you are aware of the height of the outer element, you can utilize the CSS min function to determine the appropriate width and height for the inner element in order to maintain a 16/9 ratio.

This code snippet replaces the img tag with a background image within the inner element. The height of the outer element is passed as a CSS variable, enabling calculations to be performed based on it.

Here are the outcomes:

https://i.sstatic.net/28XhP.png

.outside {
  position: relative;
  width: 500px;
  height: calc(var(--h) * 1px);
  background: red;
  overflow: hidden;
}

.inside {
  height: 0;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding-bottom: 56.25%;
  background-color: blue;
  --minw: calc(var(--h) * 16px / 9);
  width: min(100%, var(--minw));
  background-image: url(https://solvemoji-test.s3.eu-west-2.amazonaws.com/unnamed.jpg);
  background-size: auto min(100%, calc(var(--h) * 1px));
  background-position: center;
  background-repeat: no-repeat no-repeat;
}
<h1>Height is bigger</h1>

  <div class="outside" style="--h: 400">
  <div class="inside">
  </div>
</div>

<h1>Height is smaller</h1>

<div class="outside" style="--h: 200;">
  <div class="inside">
  </div>
</div>

If the height of the outer element is unknown ahead of time, using JavaScript may be necessary to set --h dynamically during runtime.

Answer №2

Using an absolute positioned image within another absolutely positioned div may not always be necessary.

.outer {
  position: relative;
  width: 500px;
  height: 200px;
  background: red;
}

.inner {
  position: absolute;
  top: 0;
  right: 72px;
  bottom: 0;
  left: 72px;
  display: flex;
  justify-content: center;
  background: blue;
}

.picture {
  max-height: 100%;
  object-fit: contain;
}
<div class="outer">
  <div class="inner>
    <img class="picture" src="https://solvemoji-test.s3.eu-west-2.amazonaws.com/unnamed.jpg" />
  </div>
</div>

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

What is the best way to store HTML in a variable as a string?

Imagine if I have a variable: let display_text = "Cats are pawsome!" I aim to show it as such: <div> <b>Cats</b> are pawsome! </div> To be clear, dynamically enclose the word "cats" whenever it shows up. ...

How can a loading bar be shown while a PHP page is loading?

I currently have an HTML form that directs to a PHP file upon submission. The PHP file takes some time to load due to background processes running, so I am interested in implementing a progress bar or alert to indicate when the file is fully loaded. Does ...

Inner Content Attribute Reveals the Markup within a Text

Hello, I am in the process of developing a simple CMS that generates blogs. The user is required to enter the blog content themselves, and I am allowing them to do so using the TinyMCE editor. I save this content in a database where the data type for the ...

In search of a mobile web UI framework solely built with CSS styling

Currently in search of a CSS framework that specializes in styling form elements and lists for optimal small screen use. The ideal framework must be CSS only, requiring minimal to no JavaScript. Something along the lines of Twitter Bootstrap would be per ...

How can I position the navigation bar ul list on the opposite side of the logo?

I've been struggling to align the text within my id= "nav-bar" to the right of the header using float:right. Despite attempting options such as using float:left and absolute positioning for the logo on the left, I haven't been successful. Even af ...

The inline variables in CSS transitions are failing to be detected

The CSS transitions are not recognizing the inline variables, or if they are, they are not receiving the correct information. Below is an illustration of how the inline variables are defined in the HTML: <p class="hidden" style="--order ...

Transferring Data Between Two Forms

Is there a way to transfer data between two HTML forms? For example, let's say we have two forms: Form 1: Contains a field for name and a submit button. Form 2: Contains fields for name, email, and a submit button. I would like to be able to fill o ...

Angular does not display results when using InnerHtml

I'm currently in the process of creating a weather application with Angular, where I need to display different icons based on the weather data received. To achieve this functionality, I have developed a function that determines the appropriate icon to ...

Preventing attribute or tag cloning in Jquery: What you need to know

I'm having some trouble with JQuery. I want to clone an attribute or tag that is dragged from one div1 to another div2, which is working fine. But the issue arises when I drag or move the position of an existing tag on div2, then the cloning process s ...

Tips for incorporating an anchor tag within an img tag in HTML?

Is it possible to add an anchor tag inside an img tag in HTML? <img src="img.jpg" alt="no img" /> I want to include the following inside the img tag: <a onclick="retake();" > Retake </a> The goal is to allow users to retake a photo by ...

The troubleshooting issue with jQuery animate Scrolltop malfunctioning

My goal is to use jQuery to scroll the page to a specific div when a button is clicked. Despite not seeing any errors in the JavaScript console, the page does not actually scroll to the desired location. I have tried placing the jQuery js file before and a ...

Steps to Retrieve and Showcase a Compilation of YouTube Clips with JavaScript

Recently, I managed to write a C code that retrieves the list of YouTube videos from the URL "*http://gdata.youtube.com/feeds/api/standardfeeds/top_rated*" using the libsoup library. By utilizing libxml2, I was able to parse the XML data and extract specif ...

Cycle through a selection and generate an HTML element for each individual item within the collection?

My Model(Objectives) stores the necessary data for iteration. Below is its code in models.py: class Objectives(models.Model): target = models.CharField(max_length=50) description = models.TextField(max_length=300) time_left= models.DateField() ...

Convert JSON data from jQuery into a modal form within a div element

I am currently working on an MVC application and attempting to populate a bootstrap modal form with data from the server. My approach involves: 1) Loading a grid with various IDs, each linked to a javascript onclick function. 2) The function retrieves th ...

Is it possible for my OAuth2 callback page to share the same HTML page? Also, what is the process for obtaining the token?

In my setup, I am working with static html and javascript along with C# Web API. One of the scenarios I encountered involves a link that triggers an oauth2 server from my HTML file named index.html. The question arises: Is it appropriate to establish the c ...

What is the best way to update a div element without the need for double clicking?

Let me explain this clearly. Currently, I have a table displaying in HTML when called. However, I want the table to disappear and show filtered results when someone enters a president's name and clicks on "Search for Presidents". I attempted using a c ...

Jquery scripts seem to have a hit-or-miss success rate

Recently, I added a couple of Jquery scripts in my header to handle the fading in of a specific CSS class and scrolling down another one. Both of these classes are initially set to display: none in CSS, with Jquery responsible for making them visible. Here ...

Store <td> in a variable

At the moment, I have a script that allows users to input an item name, along with its size, color, and other options. Each of these entries is saved as individual items with their custom specifications, such as a black t-shirt in large size. The script c ...

Transform text that represents a numerical value in any base into an actual number

Looking to convert a base36 string back to a double value. The original double is 0.3128540377812142. When converting it to base 36: (0.3128540377812142).toString(36); The results are : Chrome: 0.b9ginb6s73gd1bfel7npv0wwmi Firefox: 0.b9ginb6s73e Now, h ...

When attempting to modify styles in IE10, I consistently encounter an error message stating "Unable to evaluate expression."

Below is a JavaScript function I have created to hide an HTML tag: function hideObject(objectId) { var obj = document.getElementById(objectId); if (obj) { obj.style.display = "none"; } } I encountered a strange issue when using this ...