Preserve the video's aspect ratio while adjusting the browser size

I am currently developing a video editing tool and facing a challenge in maintaining the aspect ratio of `16:9` when resizing the screen both horizontally and vertically. While I have successfully achieved the expected behavior for horizontal resizing and vertical downsizing, I am encountering difficulties with vertical upsizing as shown here. Below is the JavaScript code snippet used to calculate the height of the video for resizing:

const calculateHeight = () => {
    // Obtain references to other elements on the page
    const header = document.querySelector('.main-navigation');
    const meshTopBar = document.querySelector('.mesh__top-bar');
    const footer = document.querySelector('.mesh__bottom-bar');
    // Get the element where window height should be applied
    const mainSection = document.querySelector('.insert-level-container');
    // Access video elements
    const editor = document.querySelector('.mesh__insert-editor-container');
    const video = document.querySelector('.mesh__insert-editor-video-container');

    // Calculate the height of the main section based on window dimensions minus the heights of other elements
    if(mainSection !== null) {
      mainSection.style.height = (window.innerHeight - header.offsetHeight - meshTopBar.offsetHeight - footer.offsetHeight) + 'px';
    }

    // Set the minimum height for the video
    video.style.minHeight = ((video.offsetWidth * 9) / 16) + 'px';

    // Resize video if its height exceeds that of the main section
    if(video.offsetHeight + 115 > mainSection.offsetHeight) {
      video.style.minHeight = video.offsetHeight - 1 + 'px';
      editor.style.maxWidth = video.offsetHeight * 16 / 9 + 'px';
    } else {
      // Logic for vertical resizing should be implemented here
    }
  }

The relevant CSS styles for these elements are:

.mesh__insert-editor-container {
    margin-left: auto;
    margin-right: auto;
}

.mesh__insert-editor-video-container {
    position: relative;
    width: 100%:
}

As for the HTML structure:

<section class="mesh__insert-editor-container flex__one flex-container flex-column horizontally-left-aligned" id="video-main-container">
    <div class="mesh__insert-editor-video-container flex-container horizontally-right-aligned flex-wrap">
        <video class="mesh__insert-editor-video-placeholder"></video>
    </div>
</section>

This code calculates the height of all elements on the page, subtracts their total from the window height to determine the main section's height, and adjusts the video size accordingly. However, I need assistance with scenarios where vertical resizing is required to upscale the video smoothly instead of abrupt changes as observed here.

If you have any suggestions or better alternatives to solve this issue, please feel free to share. Thank you!

Answer №1

Finally got it working! I implemented a fantastic CSS-only solution discovered here: https://codepen.io/EightArmsHQ/pen/BvNzrm, following the suggestion similar to BugsArePeopleToo's, from eightarmshq:

.content{
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;

  background: #555;
  box-shadow: inset 1vh 1vh 10vh 0 rgba(0,0,0,0.5);
  display: flex;


  box-sizing: border-box;
  border: 25px solid #cecece;
}

Answer №2

If you're looking for a clever solution, consider trying out the CSS aspect ratio trick: https://css-tricks.com/aspect-ratio-boxes/

This technique capitalizes on a CSS quirk where the padding based on a percentage value is relative to the element's width. By employing this method, you can create a container with the following crucial line:

padding-top: calc(9/16 * 100%);

The calculation generates the correct height according to your desired aspect ratio (e.g., 9 units tall over 16 units wide) and adjusts it relative to the width by multiplying it by 100%.

Once you have the container maintaining the aspect ratio, simply insert the content within an absolutely positioned inner div, and you should be all set. This approach ensures full responsiveness at that point.

* { box-sizing: border-box }

.outer-max-width {
  max-width: 960px;
  margin: 0 auto;
}

.aspect-ratio-box {
  width: 100%;
  padding-top: calc(9/16 * 100%);
  position: relative;
  border: 2px solid red; /* for demo visibility, remove */
}

.aspect-ratio-box-content {
  position: absolute;
  width: 100%;
  top: 0;
  left: 0;
  border: 2px solid blue; /* for demo visibility, remove */
}

.video-placeholder {
  display: block;
  width: 100%;
  height: auto;
}
<div class="outer-max-width">
  <div class="aspect-ratio-box">
    <div class="aspect-ratio-box-content">
      <img class="video-placeholder" src="https://placeimg.com/640/360/nature" />
    </div>
  </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

Tips for effectively removing a MathLive.makeMathField object

When I set up a field for editing within a modal window, my goal is to properly remove an instance of MathLive once the modal is closed. mounted() { mathField = MathLive.makeMathField(this.$refs.mathField, { virtualKeyboardMode: 'manual&a ...

Is there a way for the React select component to adjust its width automatically based on the label size?

After defining a React select component, it looks like this: <FormControl> <InputLabel id="demo-simple-select-label">Age</InputLabel> <Select labelId="demo-simple-select-label" id=&quo ...

Large objects can cause the animation to come to a standstill during

As I navigate through a large object containing 2000 elements, my react loading spinner comes to a standstill. What strategy should I take to resolve this issue without resorting to using a web worker? Currently, I am utilizing a $.each element to proces ...

Refresh information in database seamlessly without the need to reload the entire

Big shoutout to Sandeepan for the amazing support I just received! Could someone please take a look at what I may have overlooked in this code snippet... <head> <script type="text/javascript" src="jquery-1.4.2.js"></script> <script t ...

My website is currently experiencing issues with all of the CSS references not working. This problem applies to both external and internal CSS files and consistently

I'm encountering 404 errors when trying to load both internal and external files on a website through my browser. My code snippet looks like this: <link rel="stylesheet" type = "text/css" href='anoceanofsky.css'/> Despite clearing m ...

Tips on vertically centering a div within another div

Greetings, I wanted to share the code snippet I am currently using: https://jsfiddle.net/hbahar95/27/ .text.ellipsis { position: relative; font-size: 14px; color: black; font-family: sans-serif; width: 250px; /* You can adjust this as needed ...

Exploring a nested JSON structure using AngularJS's Ng-Repeat directive

I am facing an issue with displaying all elements of subcategory using Ng-Repeat. I have managed to show all events from the selected category with this code, but I am unsure how to display all activities from a specific event. I currently have this code.. ...

Finding the highest value in a multidimensional array with Javascript

How can I organize an array based on the maximum integer value it contains in a multidimensional array using JavaScript/Node? [{"data1":8,"data2":10,"data3":20.25,"data4":0}, {"data1":12,"data2":60,"data3":14.01,"data4":0}, {"data1":30,"data2":32.19,"data ...

Can anyone explain the concept of binding a click event?

My React scripts (index.js & app.js) are causing some confusion for me. There are three specific problems I need help with: First, in the index.js script, why does {count++} not increment while {count=count+1} does? Aren't they supposed to be the sam ...

What is the process for triggering an unordered list when I click on a table data cell within the Hospitals category?

Hi there! I need help with writing a JavaScript function for Hospitals in the code below. When I click on Hospitals, I want to display the values in the unordered list. Expected output: Hospitals--->onclick Bangalore| salem |Goa| Mangalore| Visakhapat ...

Is there a way to access a PHP value within a self-invoked jQuery function?

I have a page that creates n links using a foreach loop: ...some html and php code <?php foreach ($tables as $table):?> ... some elements generated ... <td><a onclick="setPortalId(<?php echo $table['id']?>);$('#file ...

Creating a dynamic form in React

After creating a functional based component, I am checking the type in a switch case to determine which form to create. const component = (props) => { let renderObject = null let obj; const renderdata = () =>{ console.log(props); ...

NodeJS encountering difficulty retrieving image every 6th try

My current project involves creating a form specifically for hotel owners. In this form, they have the ability to upload main images of their hotel, as well as images of different room types. Once a user selects images using the file browser in the input f ...

Acquiring JSON data from Node.js within Angular

After searching everywhere, I finally managed to retrieve all the data from my database using node and saved it into a file. The data is simple JSON chat logs that can be accessed through my browser with ease. Here's a snippet of how it looks: [{ " ...

Exploring Vuejs and Browserify: Leveraging LESS variables with the "@" symbol

I'm new to Vue as well and running into some issues with variables in my less files. My inclusion method looks like this: require("./colors.less"); When I try this, it seems to work at first. However, I end up receiving the following error message: ...

Show the variable in the input field without relying on the value attribute

I've been struggling to display a PHP variable in an input field without using the 'value' attribute. I attempted to use a jQuery code that I found, which was supposed to 'append' the variable to the input field, but it didn't ...

Tips for Aligning h5 Headings with Unordered Lists

My footer contains the following code: HTML: <div class="container"> <div class="row"> <div class="col-md-6"> <div class="pull-right"> <h5><u><i>Information</i></u> ...

Access to Iframe within the same domain is restricted

I am facing an issue with an Iframe embedded within my HTML page. The main domain of my website is abc.domain.local, while the domain of the Iframe is def.domain.local. Some of my tests are not returning any results, and others are displaying 'Permis ...

Creating a personalized inline script using Docusaurus

I am attempting to incorporate wowhead tooltips onto a docusaurus page. The documentation from wowhead recommends adding the following code snippet to the <head> section: <script>const whTooltips = {colorLinks: true, iconizeLinks: true, rename ...

Tips for adjusting image dimensions to accommodate small and large screens

Is there a way to make an image adapt to both mobile and full screen sizes? I attempted to make some adjustments, but unfortunately, I wasn't successful. The div class in question has a fixed width and height: <div class="pull-left thumb-con ...