Di bawah ini kita akan mempelajari cara membuat background video fullscreen dengan CSS.
Di bawah ini merupakan contoh background video fullscreen yang menutupi seluruh jendela browser:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> * { box-sizing: border-box; } body { margin: 0; font-family: Arial; font-size: 17px; } #myVideo { position: fixed; right: 0; bottom: 0; min-width: 100%; min-height: 100%; } .content { position: fixed; bottom: 0; background: rgba(0, 0, 0, 0.5); color: #f1f1f1; width: 100%; padding: 20px; } #myBtn { width: 200px; font-size: 18px; padding: 10px; border: none; background: #000; color: #fff; cursor: pointer; } #myBtn:hover { background: #ddd; color: black; } </style> </head> <body> <video autoplay muted loop id="myVideo"> <source src="https://dosenit.com/wp-content/uploads/2020/10/videoplayback-1.mp4" type="video/mp4"> Browsermu tidak mendukung video HTML5. </video> <div class="content"> <h1>SAO</h1> <p>Sword Art Online.</p> <button id="myBtn" >var video = document.getElementById("myVideo"); var btn = document.getElementById("myBtn"); function myFunction() { if (video.paused) { video.play(); btn.innerHTML = "Pause"; } else { video.pause(); btn.innerHTML = "Play"; } } </script> </body> </html>
Langkah 1) Tambahkan HTML:
Contoh
<!-- Videonya --> <video autoplay muted loop id="myVideo"> <source src="https://dosenit.com/wp-content/uploads/2020/10/videoplayback-1.mp4" type="video/mp4"> </video> <!-- Opsional: beberapa teks overlay untuk mendeskripsikan video --> <div class="content"> <h1>SAO</h1> <p>Sword Art Online.</p> <!-- Gunakan tombol untuk menjeda / memutar video dengan JavaScript --> <button id="myBtn" >
Langkah 2) Tambahkan CSS:
Contoh
/* Style pada video: 100% lebar dan tinggi untuk menutupi seluruh jendela browser */#myVideo { position: fixed; right: 0; bottom: 0; min-width: 100%; min-height: 100%; } /*Tambahkan beberapa konten di bagian bawah video / halaman */.content { position: fixed; bottom: 0; background: rgba(0, 0, 0, 0.5); color: #f1f1f1; width: 100%; padding: 20px; } /* Style pada button yang digunakan untuk jeda / memutar video */#myBtn { width: 200px; font-size: 18px; padding: 10px; border: none; background: #000; color: #fff; cursor: pointer; } #myBtn:hover { background: #ddd; color: black; }
Langkah 3) Tambahkan JavaScript:
Secara opsional, kita dapat menambahkan JavaScript untuk menjeda / memutar video dengan satu klik tombol:
Contoh
<script> // Dapatkan videonya var video = document.getElementById("myVideo"); // Dapatkan buttonnya var btn = document.getElementById("myBtn"); // Jeda dan putar video, dan ubah teks tombol function myFunction() { if (video.paused) { video.play(); btn.innerHTML = "Pause"; } else { video.pause(); btn.innerHTML = "Play"; } } </script>