Elastic video player embedded in a flexbox

I'm having an issue trying to make a responsive YouTube embed work inside a flex container alongside other content. The problem is that the container for the YouTube embed doesn't resize properly and ends up overlapping with other elements. To better illustrate this problem, I've created a demo on CodeSandbox:

Check out the demo here

import { Box, Paper } from "@mui/material";

export default function App() {
  return (
    <Box
      sx={{
        display: "flex",
        flexFlow: "column wrap",
        gap: 2,
        maxWidth: "960px"
      }}
    >
      <Box>
        <Paper
          variant="outlined"
          sx={{
            padding: 2
          }}
        >
          <h2>Some content</h2>
          <Box>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla
              maximus at enim in sollicitudin. Nam suscipit tellus sit amet
              porttitor hendrerit. Lorem ipsum dolor sit amet, consectetur
              adipiscing elit. Quisque vel dolor felis. Nulla sodales felis
              iaculis venenatis aliquam. Integer vehicula turpis a mauris
              maximus, eu sagittis ligula dignissim. In faucibus est lacus,
              auctor ornare lacus auctor ut. Morbi vitae ullamcorper nisi.
              Integer non sagittis erat.
            </p>
          </Box>
        </Paper>
      </Box>
      <Box>
        <Paper
          variant="outlined"
          sx={{
            padding: 2
          }}
        >
          <h2>YouTube player</h2>
          <Box sx={{ display: "flex" }}>
            <iframe
              src="https://www.youtube.com/embed/-opb8DdWBIM"
              title="YouTube video player"
              style={{
                margin: "0 auto",
                width: "100%",
                aspectRatio: "16 / 9"
              }}
            />
          </Box>
        </Paper>
      </Box>
      <Box>
        <Paper
          variant="outlined"
          sx={{
            padding: 2
          }}
        >
          <h2>Some other content</h2>
          <p>
            In vehicula a est non tempor. Maecenas ut leo ac arcu sollicitudin
            ullamcorper et vitae lectus. In venenatis lectus purus, non rhoncus
            ante pellentesque a. Sed sollicitudin leo sit amet odio ultricies
            pretium. Mauris eu nibh diam. Sed ante ipsum, efficitur ac leo eget,
            cursus ornare augue. Morbi aliquet porta rhoncus. Quisque ut tellus
            metus. Nam purus arcu, accumsan a dolor at, rhoncus iaculis velit.
            Class aptent taciti sociosqu ad litora torquent per conubia nostra,
            per inceptos himenaeos. Nulla augue metus, semper id varius sit
            amet, congue vitae nunc. Phasellus interdum arcu quis quam tristique
            porta. Curabitur sit amet imperdiet turpis, ut facilisis mauris.
            Aliquam sit amet commodo nisi. Quisque elementum nulla ac
            ullamcorper interdum. Aliquam interdum sed lorem a tempus.
          </p>
        </Paper>
      </Box>
    </Box>
  );
}

If you have any suggestions on how to ensure that the embed's container grows and shrinks according to the size of the video, please share your insights. Thank you for your assistance!

Answer №1

UPDATE

To address this issue, a solution has been created in the form of a codesandbox.

  1. The first step is to enclose the iframe within a container with position: "relative", and set its width to "100%".
  2. Next, adjust the container's padding-bottom property to match the desired aspect ratio using percentage values. For instance, for a 16:9 aspect ratio, specify "56.25%" (9 / 16 * 100%).
  3. For the iframe, define
    position:"absolute", top: 0, left: 0, width: "100%", height: "100%"
    to ensure proper display.
  4. In order to prevent any text below the video from being obscured, set the flexFlow: "column",

This example can be seen below:

//Containing box
<Box
    sx={{
        display: "flex",
        flexFlow: "column", // Modify this line
        gap: 2,
        maxWidth: "960px"
      }}
>

Additional code snippet

<h2>YouTube player</h2>
<Box
  sx={{
      position: "relative",
      width: "100%",
      paddingBottom: "56.25%", // 9/16 * 100% for 16:9 aspect ratio
  }}
>
    <iframe
    src="https://www.youtube.com/embed/-opb8DdWBIM"
    title="YouTube video player"
    style={{
        position: "absolute",
        top: 0,
        left: 0,
        width: "100%",
        height: "100%",
        border: 0,
        }}
    />
</Box>

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

Require assistance with displaying a menu on a website using JQuery

Is there a way to create a menu similar to the one shown in the image below?https://i.sstatic.net/QxNPL.png To learn more about this menu, you can visit their website by clicking on this Link. I have copied some code (HTML code and links to CSS and .js fi ...

When using NVDA, the close button is being read multiple times, whereas in JAWS it is being read correctly

Here is the code for a close button within a modal pop-up: <h2 class="sc-ejdXBC byjYiM MuiTypography-root MuiTypography-h6 sc-EoWXQ kOYWJk MuiDialogTitle-root" id="popupTitle"> Default Pop-UP Title <button class="sc-dm ...

Using React Typescript to create a button component with an attached image

I am currently utilizing React with Typescript. How can I incorporate an image into my button? I've attempted to do so without any errors, but the button appears blank. What's the best way to style my button element using Emotion CSS in this ...

Which is more effective: coding with just plain JavaScript and CSS, or utilizing frameworks?

As a student, is it more beneficial to focus on utilizing pure JavaScript & CSS or frameworks? And which approach is best suited for the professional field? ...

Trouble getting custom CSS media queries to function properly alongside Bootstrap 3

I've encountered an issue while using bootstrap 3 with jquery UI to implement search and select fields for the user. The CSS code seems to be working fine on larger screens, but it's completely non-functional on smaller screens. I tried applying ...

React App not functioning properly with http-proxy-middleware

After setting up proxies on my create-react-app application with http-proxy-middleware, I'm encountering a persistent 404 error whenever I click the relevant link. Following the setup instructions meticulously, I still can't seem to resolve this ...

Resizing nested elements while maintaining consistent padding dimensions

If you're looking to create a sleek foundation for a 200px wide, 30px high editable combobox that can be easily used with angular binding or other JavaScript data-binding solutions, consider the following HTML code. However, there's a desire to m ...

Modify the parent div's background color on mouseover of the child li

I want to update the background image of a parent div that contains a series of ul li elements. Here is the HTML code I am working with: <section class="list" id="services"> <div class="row"> <ul> <li>& ...

Is there a way to modify the state of my spans by utilizing onMouseHover functionality?

I am currently updating the state of my span by using document.getElementById('heart').innerHTML = 'favorite'; Do you have a more efficient method for achieving this? If so, please share your solution with me. Below is my code snippet. ...

Is there a way to add a dynamic animation of steam rising from a coffee cup to my SVG icon design?

I'm a budding graphic designer eager to master the art of SVG animated icons and coding. Recently, I created an SVG file of a beautiful cup of coffee using Illustrator and now I want to make the steam rise realistically through animation. However, des ...

Exploring Hover Effects in Reactjs and Material UI

I've been working with reactjs and material ui, but I'm having trouble changing the background color of selected items in various components, like in the SelectField. <SelectField floatingLabelText="Choose a sport" value={this.state.val ...

Adjusting Spacing Between Characters

I've been looking for a way to convert regular characters (ABC) to full-width characters (ABC), but I haven't had any luck so far. That's why I'm turning to you guys for help. Currently, I don't have any JavaScript code writt ...

Testing with React using Jest and Enzyme can be a powerful way to ensure your code is working correctly. One common task is correctly passing a

Recently, I have been trying to test the functionality of the 'video' component to see if it loads video content correctly. To achieve this, I created a reference called 'videoStream' for the 'video' component : <video ref ...

What is the secret to keeping a hover effect active?

As I hover over the buttons in my stack, a text box appears on the right side. The intention is for this text box to act as a scroll box, but it disappears when I move my mouse to scroll because it needs to be continuously hovered upon to stay active. To ...

Developing the headers for a service using React.js

As someone new to ReactJs, I'm curious about the various methods we can use to include Headers in our service Url before making a call. While I'm familiar with how GET/POST Calls are made in angular Js after including headers, I'd like to l ...

Incorporating Functions from an External Script in ReactJS/GatsbyJS

One of the functionalities on my website involves dynamically inserting a script into the head when a form element is focused, enabling it to load faster. This process is achieved using basic vanilla JS rather than React Helmet, as shown below: const handl ...

Hide the menu when a user taps on an item on mobile or tablet devices

I'm facing a unique challenge and could use some guidance. The issue is with the mobile version of my website, accessible at . On tablets or mobile devices, the menu is condensed into a button. To navigate through the menu, I have to click the button ...

What is the best way to customize the style of a component buried deep within a hierarchy? (Utilizing Material-UI's JSS Sty

The DOM structure for Material UI TextField is as follows: <FormControl... > <BaseInput ...> <input class ="MuiInputBase-input-29" ...> </BaseInput> </FormControl> When I add anything to the TextField's ...

Challenges with displaying the appropriate user interface in the dashboard according to different roles

My current project involves rendering different UI components based on selected roles such as brands, agency, or influencer. However, despite my efforts to implement the logic for this functionality, the correct UI is not being loaded and I'm struggli ...

Build a custom form for the purpose of exporting an HTML file

I am in search of a way to provide my users with various "feature" choices that will assist them in creating an HTML file for an email. I already have the code ready for each feature, but I want users to be able to select a feature (such as Hero Image Head ...