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:

If the browser is tall like a portrait phone or tablet:

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:

@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

Upon clicking the button, provide the client with the Cloudinary link

In my Next.js project, I am using Cloudinary to generate secure URLs for images. The URL is stored in the variable result.secure_url within my app/page.js file. The button functionality is defined in app/components/Cloudinary.js and imported into app/pag ...

Unresolved Issue: Jquery Modal Fails to Activate on Subsequent Click for Ajax-

When I make an Ajax call, I load HTML into a div. This HTML content contains a jQuery modal that opens when clicked. However, on the first click, the modal opens correctly. On subsequent clicks, I receive the following error in the console: Uncaught Type ...

before sending the url with fetch(url), it is adjusted

My front end code is currently fetching a URL from a local node.js server using the following snippet: fetch('http://localhost:3000/search/house') .then(.... Upon checking what is being sent to the server (via the network tab in Firefox dev ...

The error message "MVC JS deletethisproduct is not defined at HTMLAnchorElement.onclick (VM457 Index:40)" indicates that there

Upon clicking the button, I encounter this error: "deletethisproduct is not defined at HTMLAnchorElement.onclick" While I understand that using onclick is not the ideal approach, I am employing it because I need to retrieve the product id from the mode ...

Vue component does not display FabricJS image

Currently, I am facing an issue where I want to manipulate images on a canvas using FabricJS inside a VueJS app. In the view component, there is a prop called background which I pass in and then use fabric.Image.fromURL() to load it onto the canvas. Howeve ...

How to adjust the "skipNatural" boolean in AngularJS Smart-Table without altering the smart-table.js script

Looking to customize the "skipNatural" boolean in the smart-table.js file, but concerned about it being overwritten when using Bower for updates. The current setting in the Smart-Table file is as follows: ng.module('smart-table') .constant(&ap ...

CORS blocking Axios POST request to Heroku causing a Network Error 503

Using the MERN Stack, everything was functioning correctly until modifications were made to the UI (such as relocating code to different components and altering styles). The issue lies with a specific POST request, while other requests that utilize Axio ...

The scrolling feature within individual div elements seems to be malfunctioning in Ionic 2

In my current project using Ionic 2, I am faced with the task of designing a screen that contains two distinct grid views. The first grid view needs to occupy 40% of the height, allowing for scrolling within that specified area. On the other hand, the se ...

Require assistance in accurately assigning a date to a Date[] in Typescript Array without altering current elements

In my current code, I have a loop that verifies if a date is a holiday and then adds it to an array. The issue I'm facing is that whenever I assign a new element to the array, all previous data in the list gets updated to the latest element. Here&apos ...

Tips for smoothly transitioning from a simple transform to a rotate effect

I need help with an HTML element that needs to rotate when hovered over. Here is the code I have: The issue I'm facing is that I don't want a transition for translateX, only for the rotation. What steps should I take to achieve this? .cog { ...

The React syntax is malfunctioning

componentDidMount() { const restaurants = Restaurant.all() restaurants.then( rests => { this.setState({ restaurants: rests }) }) } render() { const { restauran ...

Problem encountered with AngularJS html5mode URL functionality

I am encountering an issue with my AngularJS application that does not contain any nodeJS code. The problem lies in removing the # from the URL and I have implemented ui-routes for routing. 'use strict'; var app = angular.module('myapp&apos ...

The div swiftly clicks and moves beyond the screen with animated motion

Here is a code snippet that I am working with: $(document).ready(function(){ $(".subscriptions").click(function (){ if($(".pollSlider").css("margin-right") == "-200px"){ $('.pollSlider').animate({"margin-right": '+ ...

Material-UI React is unable to identify the `underlineStyle` property on a specific HTML element

I tried implementing a custom style to change the underline color of a material-UI TextField element, following an example I found. http://www.material-ui.com/#/components/text-field Unfortunately, when I attempt to add my own styling, React does not rec ...

Simple Steps to Connect an HTML File to CSS in Windows Notepad

I have scoured the depths of the online realm in search of a method to connect HTML with CSS within the preinstalled Notepad application on Windows. Regrettably, my attempts, including utilizing the system path, proved fruitless. Is it conceivable to ach ...

Tips for arranging files within a directory in Netbeans IDE

I prefer to centralize all CSS files in a single folder for easy access. Below is the path of my CSS directory: css/sampl.css. Here, css represents the folder. This is the code snippet I am using: <link href="/CSS/sampl.css" rel="stylesheet" type="te ...

Auto-filling a form with the selected 'id' in Django using JavaScript or AJAX

I am a novice and I want the form to be autofilled when I select a vehicle ID from the template. Here are my models. class Fuel(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) previous_km = models.IntegerField(blank=False, nul ...

Customized Box with MaterialUI Styling

Currently, I am utilizing Material UI 5 for my project. To avoid repeatedly defining the same sx prop every time I create a box, I aim to build a custom box component that ensures all boxes have a consistent appearance. Upon going through the documentation ...

Using PHP to read an image blob file from an SVG

Currently, I am utilizing the Raphael JS library on the client-side to generate a chart in SVG format. However, my goal is to make this chart downloadable, which poses a challenge since SVG does not natively support this feature. Initially, I attempted to ...

How can I customize the color of Chrome's default date and time picker to a different shade of blue?

Is there a way to customize the color of the blue buttons, text, and date indicator in the native datetime picker for Chrome using CSS? https://i.stack.imgur.com/eZSaE.png ...