Next.js中覆盖Bootstrap .nav-link.active样式无效的原因
Let's break down exactly why your custom CSS isn't taking effect, and walk through actionable fixes to get your styles working as expected:
Key Issues Behind the Failure
CSS Modules Scoping & Class Name Transformation
When you usestyles.navLinkin Next.js CSS Modules, the class name gets automatically hashed (e.g.,navLink_abc123) to prevent global style conflicts. Your attempt with.tabs .navTabs .navLink.activetargets this local, hashednavLinkclass—but Bootstrap's.activeis applied to the global.nav-linkclass on the same element. The selector doesn't match because it's looking for a hashed class paired with.active, not the actual global.nav-link.activecombination on the element.Selector Priority Mismatch
Bootstrap's original selector.nav-tabs .nav-link.activehas higher specificity than your custom selector. Even if your class names were correct, Bootstrap's styles would still take precedence because their selector is more specific to the element structure.Misconception About CamelCase in CSS Modules
CamelCase in CSS Modules is just a convenience for referencing classes in JSX (e.g.,styles.navLinkworks for both.navLinkand.nav-linkin your CSS file). You don't have to use camelCase in your CSS selectors—you can still write.nav-linkdirectly if needed for clarity.
Fixes to Override the Bootstrap Styles
Option 1: Combine Local Classes with Global Bootstrap Classes
Use :global() to mark Bootstrap's global classes in your CSS Modules file, so the selector can correctly target the element without hashing the Bootstrap-specific parts:
/* Your CSS Modules file */ .tabs :global(.nav-tabs .nav-link.active) { border: 1px solid; /* Add your other override styles here */ color: #your-custom-color; background-color: #your-custom-bg; }
This works because .tabs is your local scoped class, and :global() tells CSS Modules not to hash the Bootstrap classes inside—so the selector matches the exact elements styled by Bootstrap.
Option 2: Target Local Class + Global .active Class
Since your JSX adds both styles.navLink (local) and nav-link (global) to the <a> tag, you can target the local class combined with the global .active class directly:
/* Your CSS Modules file */ .navLink:global(.active) { border: 1px solid; /* Your override styles */ }
This selector targets elements that have both your local navLink class and the global active class, with enough specificity to override Bootstrap's default styles.
Option 3: Boost Specificity (Last Resort)
If the above options don't work, you can increase your selector's specificity by adding more local classes or using !important (note: !important is generally discouraged unless absolutely necessary):
.tabs .navTabs .navLink:global(.active) { border: 1px solid !important; }
内容的提问来源于stack exchange,提问作者koque

