CSS pseudo-class - :picture-in-picture



CSS :picture-in-picture pseudo-class pop a video out into a small floating window that stays above all others, so that they can keep watching while doing other things.

Syntax

 :picture-in-picture { /* ... */ } 
The :picture-in-picture pseudo-class is not supported by Firefox and Safari browsers.

CSS :picture-in-picture Example

The following example demonstrates how to enable a Picture-in-Picture (PiP) mode for a video element and allows users to toggle it on and off using a checkbox input −

 <html> <head> <style> video { max-width: 50%; border: 1px solid; } .container { display: flex; align-items: center; margin-top: 20px; } .heading { margin-right: 10px; } .hidden { display: none; } :picture-in-picture { border: 3px solid red; } </style> </head> <body> <video id="boat_video" controls src="images/boat_video.mp4"></video> <div class="container"> <label class="heading">Picture-in-Picture Mode:</label> <!-- Label for the Picture-in-Picture mode --> <input type="checkbox" id="pipToggle" class="hidden"> <!-- Checkbox input for toggling Picture-in-Picture mode --> <span id="pipStatus" class="hidden">Off</span> <!-- Display the Picture-in-Picture status (initially hidden) --> </div> <script> // Get references to HTML elements const videoInPIP = document.getElementById('boat_video'); const pipToggle = document.getElementById('pipToggle'); const pipStatus = document.getElementById('pipStatus'); // If PIP is supported, remove the 'hidden' class from the PIP toggle and status elements if ('pictureInPictureEnabled' in document) { pipToggle.classList.remove('hidden'); // Show the toggle pipToggle.disabled = false; // Enable the toggle pipStatus.classList.remove('hidden'); // Show the status // Add an event listener to the PIP toggle checkbox to handle PIP mode switching pipToggle.addEventListener('change', switchToPIP); } // Function to switch between Picture-in-Picture mode and normal mode function switchToPIP() { // This function will be called when the user toggles the PIP checkbox // Function to change the Picture-in-Picture state function changePictureInPictureState() { if (document.pictureInPictureElement) { // Check if the document is already in PIP mode document.exitPictureInPicture().catch(() => {}); // it is, exit PIP mode } else { videoInPIP.requestPictureInPicture().catch(() => {}); // If it's not, request PIP mode for the video element } } changePictureInPictureState(); // Call the function to change the state } // Event listener to detect when the video enters PIP mode videoInPIP.addEventListener('enterpictureinpicture', () => { pipStatus.textContent = 'On'; // Update the PIP status text to 'On' }) // Event listener to detect when the video leaves PIP mode videoInPIP.addEventListener('leavepictureinpicture', () => { pipStatus.textContent = 'Off'; // Update the PIP status text to 'Off' }); </script> </body> </html> 
Advertisements