Creating a responsive design for embedding YouTube videos in web pages

I am facing an issue with embedding YouTube videos on my webpage. I have tried to make the videos responsive by using the code provided below, which works well on mobile and tablets. However, on desktops and laptops, the videos appear very large. As a workaround, I attempted to use the HTML5 video tag with width: 100% and height auto to address the responsiveness issue, but I encountered problems with video loading and buffering. Subsequently, I reverted back to using the YouTube embed option for better video loading performance, albeit sacrificing some responsiveness on laptops and desktops. You can view the webpage where the videos are embedded through the attached link.

Code-

<div class="container">
  <div class="ratio ratio-16x9">
    <iframe src="https://www.youtube.com/embed/kq7CdSf7ocA?rel=0" title="YouTube video 
      player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; 
      encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
  </div>
</div>

Answer №1

Get rid of any inline styles, specifically width and height, within the iframe element. Instead, insert the following CSS code into your stylesheet:

style.css


    .container {
        display: flex;
        justify-content: center;
    }
    
    
    iframe {
        aspect-ratio: 16 / 9;
        width: 100% !important;
    }

index.html


    <div class="container">
        <iframe src="https://www.youtube.com...."></iframe>
    </div>

Answer №2

If you're experiencing issues with the video not loading, one solution is to apply a max-width property to the iframe element.

-- For more details and code examples, visit this Fiddle link

.container {
  display: flex;
  justify-content: center;
}

iframe {
  max-width: 900px;
  max-height: 400px;
}
<head>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="13717c7c67606761726353263d233d21">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>

<div class="container">
  <div class="ratio ratio-16x9">
     <iframe src="https://www.youtube.com/embed/kq7CdSf7ocA?rel=0" title="YouTube video 
      player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; 
      encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
  </div>
 </div>

Answer №3

@Muh-Osman's method is incredibly effective. In cases where you are unable to utilize a CSS file and need to place the embed code within platforms like Webflow, this inline solution proves to be a great alternative!

  • Insert the embed code into a div container
  • Remove any specified width and height attributes
  • Most importantly, include style="aspect-ratio: 16 / 9; width: 100% !important;" at the end of the code
<div style="display: flex; justify-content: center;">
<iframe src="https://www.youtube.com/embed/VuaEV2BX5WY?si=XbTtWm3HF9FsP_2M" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen style="aspect-ratio: 16 / 9; width: 100% !important;"></iframe>
</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

AngularJS chatbox widget for interactive communication

Currently, I am in the process of developing the back-end for a web application utilizing angularJS. One of the key features is allowing users to communicate with each other through a pop-up chat box similar to those found in Gmail or Facebook. My goal is ...

jQuery Slider Showing Incorrect Images

My jQuery slider is acting strangely. It hides the first image, shows the second one, but then just repeats the cycle by showing the first image again instead of loading the third one. I'm puzzled about what could be causing this issue in my code. Do ...

Ways to improve the transition of a <video> background using CSS

My webpage features a unique 10-second video wallpaper achieved using only pure CSS. Below is the code I used: <style> video#bgvid { position: fixed; right: 0; bottom: 0; min-width: 100%; min-height: 100%; width: auto; he ...

The sidebar should remain fixed on top when viewed on mobile devices, but not when viewed on desktop

Prior to beginning a new project, I'm interested in exploring the possibility of implementing a sliding sidebar for mobile and tablets. On desktop, however, I envision a fixed sidebar that is part of the main container layout as shown below: <div ...

Error: Unexpected syntax error occurred due to the use of '===' operator

Click here for image descriptionError: There is a syntax error in line 7 of the file add.php Code: <?php require_once('db.php'); if ( !empty($_POST['name']) &&!empty($_POST['alias']) &&!empty($_POST[&apo ...

Expanding Images for Optimal Display in Responsive Design

I have a collection of large images in various sizes that I need to display without any stretching inside a container with set height. The challenge is to make the image fit perfectly within the container without distorting its proportions. I must achieve ...

Is there a way to efficiently retrieve and handle multiple $_POST records in PHP simultaneously?

I am currently working on developing a management interface that allows administrators to make bulk edits to members of a website all at once. While we already have the capability for single edits, there is a need for an option to modify all users simultan ...

Interactive phone photo gallery

I am looking to create a mobile webpage that allows me to swipe my finger left or right in the middle of the page to scroll between images. Here is an example photo: I want to be able to swipe through the images with my finger. Any suggestions on how I ...

I am having difficulty combining 2 HTML pages without the output becoming distorted

Having encountered issues when combining two HTML pages, one for a navbar and the other for a contact form in my Django project. The resultant single page appears distorted as shown in the image below. I attempted to use sections but it does not seem to re ...

What is the best way to assign attributes to multiple HTML elements using an array?

Seeking assistance to hide various sections in my HTML file upon button click, with the exception of one specific section. Encountered an error message: Uncaught TypeError: arr[i].setAttribute is not a function Here's a snippet of my code: const hide ...

Collapsing table row in Bootstrap upon button click within the same row

The snippet showcases a basic table with one row containing a button group. Upon clicking the 'main' button (the reset button), the following table row will appear. This behavior is intended only when clicking on the table row itself, not the but ...

What is the best way to extract a specific year and month from a date in a datatable using

My dataset includes performance scores of employees across various construction sites. For instance, on 2020-03-15, ALI TAHIRI was at the IHJAMN site. I need to filter this dataset by year and month. If I input 2020 for the year and 03 for the month, the d ...

How can I update the language of a button text in a React component?

Looking to update the button labels from a different language to English. Here is how it currently appears: https://i.sstatic.net/6JZ6m.png ...

Using Bootstrap to Position DIVs at the Top, Middle, and Bottom

I'm looking to create a layout with three DIVs inside a container DIV, all centered horizontally. The first DIV should be aligned at the top of the container, the second in the vertical center, and the third at the bottom. While I found some helpful t ...

Using PHP to display arrays on the screen

Currently, I am working on manipulating an array in my code. I have already accessed the array and begun the process of displaying its contents using the following code snippet: <html> <?php $file=fopen("curr_enroll_fall.csv", "r"); $records[]=fg ...

Unequal spacing between the edges of two background images

I am attempting to create two distinct "layers" of background on my webpage by encapsulating the content within a div element. Strangely, the background set for the div is being clipped before it reaches the edge of the screen, while the one designated as ...

adjust the @page rule size for different classname matches during printing

I am attempting to adjust the @page rule size based on matching classnames, however, my research has only led me to pseudo-classes which do not seem to solve my issue. Here is a snippet of my CSS: @media print { @page { margin: 13.2mm 0mm 12.9mm; ...

activate a "toggle" that allows selection of specific components to show

<span id='question'>{{QuestionText}}</span> <br> <form action={{address}}> {% for each in AnswerQuery %} <span>{{each.answer}}</span><input type='radio' name="answer"> <span>Votes:{{each.a ...

What could be causing the "function undefined" error in my HTML document?

Recently, I developed a small chat application that initially functioned well with all code contained in one HTML document. However, after separating the CSS, HTML, and JS into individual files, an issue arose when invoking the register_popup function from ...

Allowing the contenteditable attribute to function only on a single line of

My app allows users to create different lists, with the ability to edit the name. However, I am facing an issue where if a user types a new name, it should remain on only one line. I tried adding max height and overflow hidden properties, but it only hides ...