如何在保持Bootstrap导航栏原有宽度的前提下使其居中对齐
Hey there! I see you're trying to center your Bootstrap navbar without changing its 90vw width, and the usual text-center or align-center classes aren't working—let's fix that.
The Root of the Problem
Your .my-navbar class uses position: absolute, which takes the element out of the normal document flow. Regular text alignment classes won't affect absolute-positioned elements because they don't participate in the parent's text layout.
The Fix
To center an absolute-positioned element while keeping its width, you have two reliable options:
Option 1: Use left: 50% + transform: translateX(-50%)
This method shifts the element 50% from the left edge of its parent, then pulls it back 50% of its own width—perfect for centering without altering its set width.
Update your .my-navbar CSS like this:
.my-navbar{ position: absolute; z-index:999; width: 90vw; height: 10vh; padding: 20px 20px 20px 20px; background-color: white; top:20px; box-shadow:0px 4px 15px rgba(0,0,0,0.4); /* Add these two lines */ left: 50%; transform: translateX(-50%); }
Option 2: Use margin: 0 auto with left: 0 and right: 0
Alternatively, you can set left and right to 0, then use auto margins to center the element within the available space:
.my-navbar{ position: absolute; z-index:999; width: 90vw; height: 10vh; padding: 20px 20px 20px 20px; background-color: white; top:20px; box-shadow:0px 4px 15px rgba(0,0,0,0.4); /* Add these three lines */ left: 0; right: 0; margin: 0 auto; }
Why This Works
Both methods target absolute-positioned elements specifically:
- The first uses CSS transforms to adjust the element's position relative to itself, ensuring it stays centered even if the width changes later.
- The second tells the element to stretch to the parent's full width (via
left:0andright:0), then uses auto margins to push it into the center while respecting its fixed90vwwidth.
Either approach will keep your navbar at 90vw wide and perfectly centered on the page, without breaking your existing Bootstrap functionality.
内容的提问来源于stack exchange,提问作者Betty

