The issue with HTML/CSS is that it does not display video backgrounds correctly on mobile devices

On mobile, I have a code that displays a video with only a play button visible without the video itself. Once I click on play, the video starts playing as expected, but I would like to have something behind it.

Here is how it currently appears:

<div class="flex justify-center sm:mt-[-200px] z-10 relative lg:flex-row pb-12 xl:pb-12 flex-col-reverse items-center bg-gradient-to-l from-yellow-50 to-yellow-100 rounded-xl">
  <div class="video-container mt-14 rounded-lg overflow-hidden w-full max-w-[800px]">
    <!-- Heading before the video -->
    <div class="text-center text-4xl font-bold mb-10">
      Learn about
    </div>

    <!-- Video container -->
    <div class="w-[90%] mx-auto">
      <!-- Encapsulate video within a div for better control -->
      <video class="w-full h-auto rounded-lg>
          <source src=" {{ url_for( 'static', filename='home.mp4' ) }} " type="video/mp4 ">
          Your browser does not support the video tag.
      </video>
  </div>
</div>
</div>

Answer №1

To optimize the loading speed of your video content, you can enhance it by utilizing preload="metadata" in your video tag and specifying the start time of the first frame as #t=0.1 in the video source:

<video preload="metadata">
    <source src="https://example.com/foo.mp4#t=0.1" type="video/mp4">
    Your browser does not support the video tag.
</video>

If the above method doesn't yield desirable results, an alternative approach is to extract the initial frame using JavaScript:

async function captureThumbnailVideo(videoURL) {
  const video = document.createElement('video');

  video.crossOrigin = 'anonymous';
  video.src = videoURL;
  video.autoplay = true;
  video.preload = 'metadata';
  // Load video in Safari / IE11
  video.muted = true;
  video.playsInline = true;

  const canvas = document.createElement('canvas');
  let thumbnail = '';
  try {
    await video.play();
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    const context = canvas.getContext('2d');

    context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
    const thumbnailBlob = (await new Promise((resolve) =>
      canvas.toBlob(resolve, 'image/jpeg')
    )) as Blob;
    thumbnail = URL.createObjectURL(thumbnailBlob);
  } catch (e) {
    await new Promise<void>((resolve) => {
      video.onloadedmetadata = () => {
        video.currentTime = 1; //? seek to 1 second to ensure enough video data for capture

        video.onseeked = () => {
          const context = canvas.getContext('2d');

          canvas.width = video.videoWidth;
          canvas.height = video.videoHeight;

          context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight); //? draw the video frame to canvas
          video.pause();

          resolve();
        };
      };
    });
    thumbnail = canvas.toDataURL('image/png');
  }

  const duration = video.duration;

  // Destroy the video once we are done with it.
  video.pause(); // pause the video before removing it
  video.src = ''; // empty the video source to release any resources associated with it
  video.load(); // force the browser to release resources used by the video element
  video.remove();
  // Destroy the canvas once we are done with it.
  canvas.remove();

  return { thumbnail, duration };
}
const thumnail = await captureThumbnailVideo(url).then(({ thumbnail }) => {
  document.querySelector('video').setAttribute('poster', thumbnail)
}) 

If you already have a custom thumbnail image, you can easily incorporate it by adding the poster attribute to your video tag:

<video poster="/example.jpg">

Answer №2

Implement the autoplay, loop, and muted attributes within the <video> tag.

<video class="w-full h-auto rounded-lg autoplay loop muted>
  <source src="{{ url_for('static', filename='home.mp4') }}" type="video/mp4">
  Your browser does not support the video tag.
</video>
  • autoplay - Initiates automatic playback of the video
  • loop - Ensures the video continuously loops without ending
  • muted - Plays the video without sound, ideal for background purposes

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

What occurs when Click events are triggered on an <object> element?

I have set up a div, and inside that container, I embedded an SVG image using object (which I plan to manipulate later...). <div id="click-me"> some random Text <object data="some.svg" /> </div> Next, I added event listeners for t ...

Including new styles in CKEDITOR.stylesSet that pertain to multiple elements

My idea involves creating a unique bullet list style with two specific features: a. A blue arrow image replacing the standard list icon b. Very subtle dotted borders above and below each list item. I am looking to incorporate this design into CKEditor t ...

Transferring information to the controller and refreshing the interface (Single-page design)

I'm stuck on a personal project and could really use some help. If anyone has any feedback, it would be greatly appreciated. Thanks in advance. In my index.php file, I have a div with the id main-container. Inside this container, there are two separa ...

How to centrally align grids in a material-ui react application

I'm trying to center Grid items horizontally inside a Grid container, while also adding some spacing between the items. Here's the code I have so far: import React from "react"; import { makeStyles } from "@material-ui/core/styles& ...

Using jQuery's .load() method to load a PHP file can result in an exponential increase in XHR finished loading time with each subsequent load

There seems to be an issue with my code using .load() to load a PHP page into a div whenever the navbar or link is clicked. After multiple clicks, I noticed that the "XHR finished loading" increases exponentially and it appears that the same PHP file is be ...

Create a CSS menu that remains fixed at the top of the page and highlights the current submenu as

When explaining a concept, I find it easier to include a drawing to ensure clarity. https://i.stack.imgur.com/IChFy.png My goal is to keep the menu at the top of the page after scrolling past the header. https://i.stack.imgur.com/3fzJ6.png Using Bootst ...

Obtaining the Div ID After Clicking on a Link

I'm attempting to fade out a box once the X in that box is clicked. I haven't been able to make it work even after searching on Google. I managed to get it working when clicking the div itself using $(this), but my goal is for it to work when the ...

Iconic slim template for data disabling

Having an issue while working on a Rails app with slim. I am facing a problem passing HTML to slim through a button using the data-disable-with attribute. My aim is to display an icon on the button when it's clicked. = f.submit t("basket.next_step") ...

I am currently working on making my social items more responsive, however, I am encountering some issues. Any ideas or suggestions on how to resolve this

Find my resume project on GitHub at https://faizan-ul-hasnain.github.io/Resume-Project-/ and let me know how to improve it. Visit my resume project here ...

Navigate to the editing page with Thymeleaf in the spring framework, where the model attribute is passed

My goal is to redirect the request to the edit page if the server response status is failed. The updated code below provides more clarity with changed variable names and IDs for security reasons. Controller: @Controller @RequestMapping("abc") public clas ...

Discover the method for storing multiple values in local storage using a dictionary with JavaScript

I have a scenario in my code where I need to update a value without storing a new one. Let's say I need to input values in the following format: { firstname:'kuldeep', lastname:- 'patel' } After entering the values, they g ...

Reposition the div element on mobile devices using media queries

Hello, I'm facing an issue on mobile with my website: dev site Today, I implemented a dropdown menu with flags to allow language switching. However, the dropdown in mobile is appearing under the hamburger nav bar. I was thinking of using media querie ...

Using Django to render multiple images for a post

For the past few days, I have been attempting to provide the admin user with the ability to upload multiple images/slides for each individual post. One idea that came to mind was nesting a for loop inside the posts' for loop so that for every post, al ...

The ng-include feature seems to be malfunctioning

After building a basic web page using AngularJs, I ran into an issue when attempting to integrate header.htm into index.html - nothing was displaying in the browser. index.html <html> <script src="https://ajax.googleapis.com/ajax/libs/angul ...

Angular: module instantiation unsuccessful

Just getting started with Angular and running into an issue where the module seems to be unavailable. https://docs.angularjs.org/error/$injector/nomod?p0=plopApp My code is very basic at the moment, just setting things up: @section scripts{ <script s ...

To showcase the entire contents of a specific column from one table onto a different table on the following page once the box is ticked

Everything seems to be running smoothly, except for one issue. When a row contains the value "hello world" in a column on the first page, it only displays "hello" in the item column on the second page. I'd like it to show the full value "hello world" ...

What is the best way to position a div in relation to a table header (th) but not inside it?

I'm trying to create a table header that displays a help text (div) when clicked on. However, the help div is causing the table header to be larger than the other headers. Below is the code snippet: #help_box { border-radius: 20px; ba ...

What is the process for inserting a scroll bar within a div element?

   I have recently created a webpage using some divs, along with a bit of CSS and JavaScript. I am struggling to figure out how to add a scrollbar to one of my divs. The code is not overly complex, as it includes both CSS and JavaScript. <html> & ...

Unable to retrieve all form properties when using enctype='multipart/form-data'

Recently, my NodeJS server has been successfully uploading files to Amazon using a secret form. However, in an effort to enhance security measures, I decided to introduce a password field to the form. Unfortunately, upon doing so, I encountered an issue wh ...

What are the different methods for completing a form?

From what I understand, there are 2 methods for submitting a form. For instance, in asp.net, there is the Button.UseSubmitBehavior property which Specifies whether the Button control uses the client browser's submit mechanism or the ASP.NET postb ...