HTML Video as Full-Screen Background: A Comprehensive Guide
To make a video tag in HTML full height and width as a background, you can use CSS to style the video tag and set it as a background using the 'background-size' property.
Here's an example code:
HTML:
<video id='bg-video' autoplay loop muted>
<source src='your-video-source.mp4' type='video/mp4'>
</video>
CSS:
#bg-video {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
z-index: -1;
background-color: #000;
}
@media (min-aspect-ratio: 16/9) {
#bg-video {
height: 300%;
top: -100%;
}
}
@media (max-aspect-ratio: 16/9) {
#bg-video {
width: 300%;
left: -100%;
}
}
Explanation:
- The video tag is given an ID of 'bg-video' and has the attributes autoplay, loop, and muted to make it play continuously without sound.
- In the CSS, we position the video tag fixed to the top left corner of the screen and set its width and height to 100% to make it fill the entire screen.
- We use the 'object-fit' property with the value 'cover' to ensure that the video fills the entire screen without distorting its aspect ratio.
- We set the 'z-index' property to -1 to ensure that the video is behind all other content on the page.
- We also set a 'background-color' of black in case the video takes some time to load or if the user's browser doesn't support HTML5 video.
- We use media queries to adjust the size of the video tag depending on the aspect ratio of the user's screen. If the aspect ratio is wider than 16:9 (e.g. on a desktop monitor), we set the height of the video to 300% and move it up by 100% to center it vertically. If the aspect ratio is narrower than 16:9 (e.g. on a smartphone), we set the width of the video to 300% and move it left by 100% to center it horizontally.
Note: This code assumes that your video file is in MP4 format. You may need to provide additional source tags for other formats (e.g. WebM, Ogg) to ensure compatibility across different browsers.
原文地址: https://www.cveoy.top/t/topic/nWxx 著作权归作者所有。请勿转载和采集!