如何让section元素显示在全屏video下方?WebKit浏览器兼容问题
Let’s start with the root cause: WebKit-based browsers (Chrome, Safari) handle fullscreen video rendering differently than Firefox and Edge. When a video enters fullscreen mode, it gets placed into a top-level rendering layer that bypasses normal DOM stacking context rules—tweaking z-index alone won’t fix this because your sections live in a separate rendering context.
Here are two reliable fixes you can implement, depending on your layout needs:
1. CSS-Only Solution (WebKit-Specific)
We can target WebKit’s fullscreen behaviors directly to force sections into a lower stacking context:
/* Target WebKit browsers exclusively */ @media screen and (-webkit-min-device-pixel-ratio: 0) { /* Push sections after the video below fullscreen content */ :fullscreen + section, :-webkit-full-screen + section { z-index: -1 !important; position: relative; /* Reset any stacking context-creating properties if needed */ transform: none !important; } /* Ensure the fullscreen video container stays locked to the top */ video::-webkit-media-controls-fullscreen-container { z-index: 2147483647 !important; /* Max possible z-index value */ } }
The !important flag is necessary here because WebKit’s default fullscreen styles have extremely high specificity. Make sure your sections don’t use position: fixed or transform properties that create their own stacking contexts—if they do, add those resets to the rule above.
2. JavaScript Solution (More Granular Control)
If the CSS fix doesn’t account for your dynamic layout, use event listeners to adjust section styles when the video enters/exits fullscreen:
const targetVideo = document.querySelector('section:nth-of-type(2) video'); // Listen for fullscreen state changes (covers WebKit and standard APIs) targetVideo.addEventListener('fullscreenchange', toggleSectionStacking); targetVideo.addEventListener('webkitfullscreenchange', toggleSectionStacking); function toggleSectionStacking() { const isFullscreen = document.fullscreenElement || document.webkitFullscreenElement; // Adjust the selector to target the sections you want below the video const sectionsToLower = document.querySelectorAll('section:nth-of-type(n+3)'); if (isFullscreen) { sectionsToLower.forEach(section => { section.style.zIndex = '-1'; section.style.position = 'relative'; }); } else { // Reset styles to preserve normal layout when exiting fullscreen sectionsToLower.forEach(section => { section.style.zIndex = ''; section.style.position = ''; }); } }
Troubleshooting Notes
- If sections still appear on top, check parent elements of your sections—any parent with a set
z-indexcreates a stacking context that blocks negative z-index values from working. Remove or adjust those parentz-indexsettings. - Avoid using
transform: translateZ(0)orwill-change: transformon sections that need to stay below the video—these properties create independent stacking contexts that override z-index rules.
内容的提问来源于stack exchange,提问作者Bryce

