Preserving the video's aspect ratio by limiting the width and height to a maximum of 100%

I am trying to integrate a YouTube video using their embed code in a "pop-up". However, I am facing an issue where the video does not resize to fit within the height of its parent. I want it to be constrained by the div#pop-up that contains the video. Currently, the video will stretch as wide as possible and maintain its aspect ratio for height even if it exceeds the parent's height. My goal is for the video to fill the parent's padding or margin while staying centered and maintaining a 16:9 aspect ratio.

I would prefer not to use jQuery, so JavaScript might be a suitable option.

*{
  margin:0;
  padding:0;
}
#pop-up{
  width:100%;
  height:100vh;
  padding:5%;
  box-sizing: border-box;
  background:rgba(0,0,0,0.2);
}
<div id="pop-up">
  <!--Youtube embed code-->
  <div style="position:relative;height:0;padding-bottom:56.25%"><iframe src="https://www.youtube.com/embed/ZLtNZuQzJ4w?ecver=2" width="640" height="360" frameborder="0" style="position:absolute;width:100%;height:100%;left:0" allowfullscreen></iframe></div>
</div>

Here's a visual example of what I'm aiming for:

If the browser is wide like a computer or landscape phone: https://i.sstatic.net/FsBWC.jpg

If the browser is tall like a portrait phone or tablet:https://i.sstatic.net/M7HgM.jpg

Answer №1

I have made some adjustments to the styling based on your preferences.

Please check if these changes work for you.

As requested, here is how the layout looks now:

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

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

@media (max-width: 1024px) {
  body #pop-up iframe {
    max-height: 34.6vh;
  }
}

* {
  margin: 0;
  padding: 0;
}

#pop-up {
  width: 100%;
  height: 100%;
  padding: 5%;
  box-sizing: border-box;
  background: rgba(0, 0, 0, 0.2);
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
}

#pop-up iframe {
  width: 100%;
  height: 100%;
  max-width: 1024px;
  max-height: 576px;
}
<div id="pop-up">
  <iframe src="https://www.youtube.com/embed/ZLtNZuQzJ4w?ecver=2" width="640" height="360" frameborder="0" allowfullscreen></iframe>
</div>

Answer №2

To solve this issue, I implemented media queries to track the window's aspect ratio. Since my pop-up initially covers the entire window, I needed to ensure that the image used had a 16:9 aspect ratio at 100% height. By utilizing inline-block to determine the image size and absolute positioning with 'top', 'right', 'bottom', and 'left' set to 0, I was able to apply the parent's size to the video container.

For dynamic resizing upon changes in child element size or window resize events, I incorporated a simple JavaScript function to remove and reapply the width setting after each adjustment.

I abandoned the idea of centered videos and decided to utilize the leftover space for additional content instead.

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

Utilizing nested createHtmlOutputFromFile in Google Apps Script HtmlService to generate jQuery code

Embarking on a new journey, I am diving headfirst into the world of JQuery WebApp with Google Apps Script. Every day is filled with new discoveries and excitement as I immerse myself in learning to piece things together. Starting off with some examples an ...

What is the best way to apply CSS styles to a child div element in Next.js?

I'm currently working on enhancing the menu bar for a website project. Utilizing nextjs for my application I am aiming to customize the look of the anchor tag, however, encountering some issues with it not rendering correctly. Here is a snippet of ...

Problem with Ionic 2 local storage: struggling to store retrieved value in a variable

Struggling to assign the retrieved value from a .get function to a variable declared outside of it. var dt; //fetching data this.local.get('didTutorial').then((value) => { alert(value); dt = value; }) console.log("Local Storage value: " ...

Finding documents in MongoDB where the size of an array exceeds 1

Looking to retrieve documents with an array size greater than 1 in my MongoDB collection Here is a snapshot of my collection: { "_id" : ObjectId("5eaaeedd00101108e1123452"), "type" : ["admin","teacher" ...

Storing the results of an Ajax call in a global variable

What is the best way to store and access the output of an ajax call within a global variable? let globalOutput = []; $.ajax({ type: "GET", url: uri, dataType : "json", contentType: "application/json", data: { input: filterVa ...

Browser behavior for animating background-position varies

check out this interactive demo - The objective is to create a unique perspective effect while scrolling, specifically on the background. The effect functions properly on Chrome and IE7, IE8 versions; however: Issues arise with IE9, where the background ...

Tips for saving a web page using Selenium Webdriver in JavaScript

Is there a way to programmatically save an entire webpage using Selenium Webdriver JS in Firefox? I have been able to bring up the Save As dialog with the following code: driver.findElement(webdriver.By.tagName('html')).sendKeys(Key.CONTROL + &ap ...

Button press triggers the fadeIn function successfully, but the keypress event does not have the same effect

I'm currently facing an issue with two div elements on my webpage. I want only one of them to be visible at a time, depending on which key is pressed. If the 1 key is pressed, I want 'div1' to fadeIn (if it's not already visible) and fo ...

A guide on updating CSS content dynamically within ExtJS

In my resource folder, I have a CSS file that contains some values which I need to change or add based on certain conditions. However, I'm struggling to figure out how to achieve this. Here is an example of the code: triggers: { clear: { ...

exploring numerous boxes in an engaging and educational tutorial

Explaining this in the title was a bit tricky, but what I want to create is an interactive tutorial. In this tutorial, the user will click on an area or product they want to clean or use for cleaning. After clicking, another box with relevant information w ...

Best Practices for Handling an Abundance of Data in React or Java

I am facing a challenge with my project setup, where I have the front end in ReactJS and the backend API in Spring Boot. The task at hand is to display a drop down list filled with records retrieved from the API. Here's the scenario: I receive a list ...

Building a Dynamic CSS Grid

Today is the first time I'm reaching out for help rather than figuring things out on my own. I'm currently working on a website layout that consists of visible tiles all with equal sizes, forming a grid structure. The challenge I face is making t ...

Issue with attaching dynamic events is not functioning as expected

var smartActionsId = ['smartActions1','smartActions5','smartActions10']; for (let i in smartActionsId) { console.log("smartActionsId ="+smartActionsId[i]); $('#' + smartActionsId[i] + ' select').c ...

Continuously receiving the value of undefined

I am currently working on a JavaScript Backbone project and I have declared a global object as follows: window.App = { Vent: _.extend({}, Backbone.Events) } In the initialize function, I have done the following: initialize: function () { window.App ...

How can we align the Recaptcha and Send button with the text box in a DIV using CSS exclusively?

Struggling to line up my send button and recaptcha with the end of the text box in a contact form in a responsive manner. I've spent days trying to make it work without success. Check out my jsfiddle here: Example Here's the current CSS: /*cust ...

Why isn't the AngularJS injected view resizing to fit the container?

As a novice delving into a project in the MEAN stack, I'm encountering inconsistent HTML previews. When I view it independently versus running it from the project, the display varies. Here's the intended appearance (in standalone preview): imgu ...

Why is the option value not visible in the dropdown selection list?

On my website, I am trying to use a date range to aggregate data from MySQL and display it based on the selected time frame. However, I am facing an issue where the values for each option in the drop-down menus are not showing up. Below is the PHP code I a ...

What is the best way to create a video that adjusts to different screen sizes within

I am working on the responsive version of client's website and I stumbled upon this issue - when I make smaller the browser window, the youtube video is not centered - the padding-right: 10px; is ignored - why? How could I fix that? Here is the CSS ...

Load a page and sprinkle some contents with a slide effect

I am brand new to jQuery and just starting out, so please excuse me if this question seems basic or silly. I would like the header and footer of my page to stay in place while the center content slides in from the right side when the page loads. This websi ...

Instructions on opening a modal and changing the source of the iframe within the modal

I currently have a modal within my application that is triggered by Bootstrap: <div class="modal full-page fade" tabindex="-1" role="dialog" id="fullpageModal"> <div class="full-page-content"> <button type="button" class="close" d ...