固定宽度(1170px)网站Lightbox屏幕相对位置实现方案求助
Got it, let's tackle this problem step by step. You want your Lightbox to line up with the left edge of your fixed 1170px-wide content (instead of sticking to the screen's right edge). Here are a few reliable solutions depending on your needs:
1. Pure CSS Solution (Simplest Option)
If you don't need to support really old browsers (all modern browsers handle this fine), you can use CSS calc() to dynamically calculate the right offset directly in your stylesheet. This avoids any JavaScript overhead.
/* Replace .lightbox-element with your actual Lightbox class/id */ .lightbox-element { position: fixed; /* Or absolute, depending on your existing setup */ right: calc((100vw - 1170px) / 2); /* Keep your other existing Lightbox styles here (width, height, background, etc.) */ }
How this works:
100vwis the full width of the viewport (screen)- Subtract your fixed content width (1170px) to get the total empty space on both sides of your content
- Divide by 2 to get the width of the empty space on one side—this is exactly how far right we need to push the Lightbox to align it with your content's left edge.
2. jQuery Solution (Dynamic & Compatible)
If you need broader browser support or want to adjust the position when the window resizes, use this jQuery approach. It calculates the offset on page load and updates it whenever the screen size changes.
function setLightboxPosition() { const contentWidth = 1170; const screenWidth = $(window).width(); const rightOffset = (screenWidth - contentWidth) / 2; // Target your Lightbox element (update the selector if needed) $('.lightbox-element').css('right', `${rightOffset}px`); } // Run on page load $(document).ready(function() { setLightboxPosition(); }); // Re-run when window is resized $(window).resize(function() { setLightboxPosition(); });
3. Vanilla JavaScript Solution (No jQuery Needed)
If you prefer not to use jQuery, here's the native JS version that does the exact same thing:
function setLightboxPosition() { const contentWidth = 1170; const screenWidth = window.innerWidth; const rightOffset = (screenWidth - contentWidth) / 2; // Target your Lightbox element (update the selector if needed) const lightbox = document.querySelector('.lightbox-element'); if (lightbox) { lightbox.style.right = `${rightOffset}px`; } } // Run when the DOM is fully loaded document.addEventListener('DOMContentLoaded', function() { setLightboxPosition(); }); // Re-run when window resizes window.addEventListener('resize', setLightboxPosition);
Important Notes:
- Make sure your Lightbox element has
position: fixedorposition: absoluteset—otherwise therightCSS property won't work as expected. - Double-check your Lightbox selector (
.lightbox-elementin the examples) matches the actual class or ID used in your site's code.
内容的提问来源于stack exchange,提问作者Gaston Coroleu

