Fotorama:小尺寸非拉伸图片能否设置全屏宽度字幕?
Absolutely! You can make Fotorama captions span the full available width even when your images are smaller than the viewport and not set to stretch. Let’s fix that narrow caption issue with two straightforward approaches:
1. Custom CSS (Quickest Fix)
Fotorama by default constrains captions to the width of the image frame. To override this, target the caption container and force it to match the width of the Fotorama stage:
/* Make captions full-width relative to the Fotorama container */ .fotorama__caption { width: 100% !important; left: 0 !important; box-sizing: border-box; padding: 12px 20px; /* Adjust padding to avoid text touching edges */ background-color: rgba(0, 0, 0, 0.7); /* Optional: Keep background consistent */ } /* Optional: Only apply when images aren't fullscreen */ .fotorama__stage__frame:not(.fotorama__stage__frame--fullscreen) .fotorama__caption { position: absolute; left: 50%; transform: translateX(-50%); }
Why this works: The !important flag overrides Fotorama's inline styles, and box-sizing: border-box ensures padding doesn't make the caption wider than the container. The optional rule ensures this only applies to non-fullscreen images, preserving normal behavior when images are stretched.
2. JavaScript (Dynamic Adaptation)
If you need more control (e.g., handling responsive resizes or dynamic content), use Fotorama's built-in events to adjust captions on the fly:
$('.fotorama').fotorama({ ready: function() { const fotorama = this; // Adjust caption width when a new image loads fotorama.on('show', function() { const caption = $('.fotorama__caption', fotorama.stage); if (caption.length) { caption.css({ width: fotorama.$stage.width(), left: 0, boxSizing: 'border-box', padding: '12px 20px' }); } }); // Handle window resizes to keep captions full-width $(window).on('resize', function() { const caption = $('.fotorama__caption', fotorama.stage); if (caption.length) { caption.width(fotorama.$stage.width()); } }); } });
Why this works: The show event triggers whenever a new image is displayed, and we dynamically set the caption width to match the Fotorama stage's current width. The resize listener ensures captions adapt if the window size changes.
Key Notes
- Avoid overusing
!importantwhere possible: If you're using a custom Fotorama build, you might be able to modify the core styles instead of overriding them. - Test across browsers: Fotorama's class names are consistent in recent versions, but double-check for older releases.
- Preserve accessibility: Ensure caption text remains readable against your image backgrounds (adjust the background opacity if needed).
内容的提问来源于stack exchange,提问作者xiatica

