Video HTML

7 min read

How to add a video background in HTML?

Adding a video background to your website can be a great way to make it more visually appealing and engaging. In this blog post, we'll show you how to add a video background in HTML.

Feature image
How to add a video background in HTML?

Website backgrounds play a pivotal role in elevating a website's visual appeal, and there are myriad possibilities to transform them using CSS, HTML, and JavaScript. One particularly attractive option is using captivating videos as your background. In this guide, we'll dive into the art of embedding videos as website backgrounds using CSS and JavaScript. We'll also craft them to be responsive, interactive, and performance-efficient.

Schedule a Demo with Our Video Expert!

Discover how Gumlet can help you build a cutting-edge video streaming infrastructure.

How to add Video Background in HTML?

Here are three steps to create an HTML page with a video background, styled overlay content, and a button to control video playback.

Step 1: Add HTML - Adding the Video

In this step, you create a background video HTML structure that includes a video element and overlay content. You embed the video using the <video> element and provide the source file (in this example, "sample.mp4"). You can also add optional overlay content and a button for pausing and playing the video:

<!-- The video -->
<video autoplay muted loop id="myVideo">
  <source src="sample.mp4" type="video/mp4">
</video>
<!-- Optional: some overlay text to describe the video -->
<div class="content">
  <h1>Heading</h1>
  <p>Lorem ipsum...</p>
  <!-- Use a button to pause/play the video with JavaScript -->
  <button id="myBtn" onclick="myFunction()">Pause</button>
</div>

Step 2: Add CSS - Styling the Video

Next, you define the background video CSS styles to control the appearance and positioning of the video and overlay content, to achieve the desired visual effect. The video is set to cover the entire window, and the overlay content is styled with a semi-transparent background.

Step 3: Add Javascript - Play/Pause The Video (Optional)

If you want to provide the functionality to pause and play the video, you include JavaScript. We include a play/pause button using their respective IDs—such that, when the button is clicked, it toggles between playing and pausing the video, and the button text changes accordingly, (either "Pause" or "Play").

<script>
// Get the video
var video = document.getElementById("myVideo");
// Get the button
var btn = document.getElementById("myBtn");
// Pause and play the video, and change the button text
function myFunction() {
  if (video.paused) {
    video.play();
    btn.innerHTML = "Pause";
  } else {
    video.pause();
    btn.innerHTML = "Play";
  }
}
</script>

HTML Video Background - Customisations

Here are steps to customize your website background video:

Muting the background video’s sound

To ensure a polished user experience with video backgrounds, simply add the "muted" attribute to your video tag. This attribute prevents unwanted audio disruptions:

<video src="video.mp4" muted autoplay loop></video>

Making Video Background responsive

Achieving responsiveness in video backgrounds is crucial for delivering a seamless user experience.

To maintain the standard 16:9 aspect ratio (widely accepted on modern devices), utilize media queries to adapt the video's dimensions. For screens with a minimum aspect ratio of 16:9, scale the width while keeping the height auto-adjusted. Conversely, for screens with a maximum aspect ratio of 16:9, auto-adjust the width while maintaining the height at 100%. This will ensure that your video background adjusts responsively as the window size changes.

@media (min-aspect-ratio: 16/9) {
  video {
    width: 100%;
    height: auto;
  }
}
@media (max-aspect-ratio: 16/9) {
  video {
    width: auto;
    height: 100%;
  }
}

For optimal performance on mobile devices, consider disabling the video and replacing it with a static image when the screen size is below 768px. Here's an example of how to achieve this:

@media (max-width: 768px) {
    video {
    display: none;
  }
  #main{
    background: url(/snapshot.png);
    background-size: cover;
  }
}

Adding Gradient and Color Overlays

To improve legibility and reduce distraction, overlays are invaluable tools. You can apply either gradient or color overlays to your video background. Start by including an empty div in your HTML code to act as the overlay.

In this example, we'll use a div with the class "overlay."

<body>
    <section id="#main">
      <div class="overlay"></div>
      <video src="video.mp4" muted autoplay loop></video>
    </section>
</body>

Next, adjust the video background's size and include color with the background property:

.overlay{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(48,25,52,0.75);
}

For color overlays, use CSS to position the overlay div, covering the entire video background, and set the background property to your desired color with an adjustable opacity level. Here is a sample code:

.overlay{
  background-image: linear-gradient(to right, rgba(34,35,46,0.75), 
  rgba(0,194,203,0.5));
}

Adding Video Background Slider

Consider implementing a Video Background Slider to elevate user engagement and captivate your audience further. You can employ JavaScript or libraries like Slick Slider or Swiper to gracefully cycle through multiple videos and display a sequence of videos, each seamlessly transitioning into the next—creating a compelling backdrop for your webpage:

<div class="video-slider">
  <video src="video1.mp4" muted autoplay loop></video>
  <video src="video2.mp4" muted autoplay loop></video>
  <video src="video3.mp4" muted autoplay loop></video>
</div>
<script src="slider-library.js"></script>

How to optimize the background video for the webpage?

Here are some top tips to optimize your webpage background video for maximum visibility and aesthetic appeal:

  • Keep engagement brief: Maintain background video clips between 15 to 20 seconds; extended durations are superfluous and may alienate your audience.
  • Choose the resolution strategically: Opt for standard HD dimensions, precisely 720p (1280 x 720 pixels), to balance visual quality and bandwidth efficiency.
  • Make it SEO-Friendly: Prioritize your web page's SEO by configuring metadata for your background video; include descriptive video titles, relevant keywords, and compelling descriptions that align with your website's content.
  • Choose the right frame rate: Employ a frame rate of 24 or 25 frames per second—it will strike the ideal balance for web videos, resulting in compact file sizes.
  • Mute the video: As background videos don't auto-play with sound, eliminate the audio channel when exporting the video.
  • Choose the poster image carefully: It's a good idea to match the video's initial frame for seamless loading and aesthetic appeal.
  • Ensure browser compatibility: Use both MP4 and WebM formats when exporting videos to ensure flawless playback across diverse browsers.
  • Ensure readability: Have sufficient contrast between the video backdrop and overlaid elements; you may use semi-transparent color overlays for enhanced legibility.
  • Maintain user-friendliness: Give users a JavaScript-based pause button if they prefer to disable background video motion. You can also consider automated video pausing for looping videos after a specified duration.

To optimize the background video for your webpage, consider using Gumlet's embed code, which provides a convenient and seamless solution. Check out the sample code below, which has a customizable player, video metadata configuration, SEO snippet, and security features.

<iframe width="1200" height="675" 
        src="https://play.gumlet.io/embed/{{asset_id}}" 
        title="Gumlet video player" 
        frameBorder="0" 
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; fullscreen">
</iframe>

You can tailor your player settings easily by adjusting parameters within the iframe code, like width, resolution, and height, to suit your design needs.

How to fix issues with the video background?

You will likely encounter multiple issues when perfecting your website background video. Here's how to address them:

  • Videos Not Playing: Make sure you're covering the basics here. Check your video formats — MP4 and WebM formats are the most widely supported. Next, ensure the video file path is correct; even a small typo can cause issues. Finally, pay attention to the video codec, with H.264 being a safe choice for compatibility. And, of course, confirm that you have the "autoplay" attribute set within your video tag.
  • Videos Not Responsive: Use CSS to define video dimensions as percentages, especially setting the width to 100%. To preserve aspect ratios, use media queries and consider hosting your videos using a service like Gumlet that handles responsiveness automatically.
  • Not Working on Mobile: Ensure your video files are optimized for mobile devices in terms of both format and size. Keep in mind that some mobile browsers require videos to be muted for autoplay to work. If needed, you can use media queries to seamlessly switch to an image or static background for smaller screens.
  • Browser Compatibility: The best approach here is to test your webpage on various browsers and versions to identify and address specific issues. Always check the compatibility of your chosen video formats with major browsers. Use your video tag's <source> element to cover all bases to provide multiple video formats.

Key Takeaways

Adding video backgrounds to your website can elevate its visual appeal but requires careful implementation. You can use HTML for embedding, CSS for styling, and JavaScript for enhancing overall functionality and, thus, user interaction. It is essential to optimize your video by incorporating best practices like muting audio, ensuring responsiveness across devices and browsers, and ensuring maximum readability with features like overlays.

FAQs

What are the benefits of using a video background?

Using a video background on your website can greatly enhance its visual appeal and engagement. They can effectively convey messages, emotions, or brand identity, grabbing visitors' attention and encouraging them to explore your content further. This in turn fosters user retention and conversions.

How do I find video backgrounds for my webpage?

To find video backgrounds,

  • Check out platforms like Shutterstock, Adobe Stock, or Pexels for a wide selection of video backgrounds.
  • You can customize your own backgrounds to match your brand using video editing software like Adobe Premiere or Final Cut Pro.
  • Look for free resources like Pexels, offering high-quality video backgrounds.
  • You'll find plenty of web design tools and templates that offer built-in video background options.

What is the duration of the video that we add?

When adding a video background to your webpage, it's recommended to keep the duration between 15 to 20 seconds. Shorter videos keep users engaged without overwhelming them. Remember, the goal is to enhance your site's aesthetics and capture attention, not to deliver extensive content.

Similar readings

Share this Article:

For more such content