AMP-lightbox内嵌amp-video尺寸适配问题求助
Fix: AMP Video & Poster Overflowing in amp-lightbox Modal
You’re absolutely right about the root cause—since amp-lightbox starts as display:none, AMP’s responsive layout calculations can’t run properly on the hidden amp-video element, leading to overflow issues. Here’s how to fix it with targeted CSS and AMP layout adjustments:
Step 1: Adjust the Modal Container CSS
First, we’ll modify the .modal-body to maintain a consistent aspect ratio (matching your video) and hide overflow. We’ll also add a nested container to properly constrain the video:
.modal-body { background-color: #fefefe; margin: 75px auto 0; padding: 20px; border: 1px solid #888; width: 90%; max-width: 800px; /* Prevents modal from getting too wide on large screens */ position: relative; height: 0; /* Replace fixed height with aspect ratio padding */ padding-top: 56.25%; /* 16:9 aspect ratio (9/16 = 0.5625) */ overflow: hidden; /* Clip any overflowing content */ } .video-container { position: absolute; top: 20px; left: 20px; right: 20px; bottom: 20px; /* Fill the space inside .modal-body's padding */ }
Step 2: Update the amp-video Layout
Change the amp-video to use layout="fill" so it adapts to its parent container, and add object-fit to control how the video/poster scales:
<a class="travel-results-result-link block relative" on="tap:video-1"> <amp-img class="block rounded" width="346" height="200" noloading="" src="/images/video/image01.jpg"></amp-img> </a> <amp-lightbox id="video-1" layout="nodisplay"> <div class="lightbox" on="tap:video-1.close" role="button" tabindex="0"> <div class="modal-body"> <div class="video-container"> <amp-video controls layout="fill" poster="/images/video/image01.jpg" object-fit="contain" > <source src="/videos/gail-video-1.mp4" type="video/mp4" /> <div fallback> <p>This browser does not support the video element.</p> </div> </amp-video> </div> </div> </div> </amp-lightbox>
Key Changes Explained
- Aspect Ratio Padding: Using
padding-top: 56.25%ensures the modal maintains a 16:9 ratio (adjust this to match your video’s aspect ratio—e.g., 75% for 4:3). This lets AMP calculate the correct dimensions even when the lightbox is hidden initially. layout="fill": Makes theamp-videofill its parent.video-container, so it automatically adapts to the modal’s size.object-fit: contain: Ensures the video and poster are fully visible without stretching (usecoverinstead if you want to fill the container and crop edges).- Consistent Paths: Fixed the poster path to match the
amp-imgsource to avoid broken images.
内容的提问来源于stack exchange,提问作者Matthew Flynn
相关产品推荐
相关产品推荐

