如何实现页眉图片居中于整个页面而非浏览器窗口?
Got it, let's sort this out for you. The issue right now is that your header image is centering relative to the browser's viewport (the visible window), not the actual page content container. Here's why and how to fix it:
What's Wrong With the Current Code
Your #wrapper and #header have margin: 0 auto, but without an explicit width or max-width set on #wrapper, it defaults to taking up 100% of the viewport width. That means text-align: center on the header just centers the image within the full window, which shifts as you resize the browser.
The Fix
We need to constrain your page content to a fixed maximum width, so the image aligns with that container's center instead of the viewport. Here's the adjusted CSS:
#wrapper { margin: 0 auto; max-width: 1200px; /* Adjust this to your desired maximum page width (e.g., 1000px, 1440px) */ width: 100%; /* Ensures the wrapper fills the viewport when it's smaller than max-width */ } #header { margin: 0 auto; background: #FFFFFF; text-align: center; width: 100%; /* Matches the header width to the wrapper */ } #header img { max-width: 40%; height: auto; }
Breakdown of Changes
max-width: 1200pxon#wrapper: This locks your page content to a maximum width—when the browser window is wider than this, the wrapper stays centered at 1200px instead of stretching. This is the core fix for anchoring the image to the page's center.width: 100%on#wrapper: Keeps the layout responsive for smaller screens, ensuring the wrapper fills the viewport when it's narrower than your set max-width.width: 100%on#header: Makes sure the header matches the wrapper's width, so thetext-align: centertargets the page container's center, not the viewport.
If you want a fixed-width page (not responsive), you can replace max-width: 1200px with width: 1200px instead—just note that it won't shrink on smaller screens unless you add media queries.
内容的提问来源于stack exchange,提问作者Gunther Valentine

