如何在特定CSS类生效时修改指定ID元素的CSS样式?
Hey there! Let's get this sorted out for you. The problem with your initial CSS is that native CSS doesn't support selector nesting (that syntax works for preprocessors like Sass/Less, but plain CSS won't interpret it correctly). Here's how to fix it:
Correct Native CSS Syntax
Instead of nesting the #sidebarMenu selector inside .nav-collapse.in.collapse, you need to chain them together to target the sidebar only when the parent menu container has those active classes:
/* Target #sidebarMenu only when its ancestor has .nav-collapse.in.collapse classes */ .nav-collapse.in.collapse #sidebarMenu { width: min-content; }
Why This Works for Your Toggle Scenario
Since you're using what looks like Bootstrap's collapse component, the .in class is dynamically added/removed when the menu is toggled open/closed. This means:
- When the menu is toggled open,
.nav-collapse.in.collapseis present, so#sidebarMenugets thewidth: min-contentstyle. - When the menu is toggled closed, the
.inclass is removed, so the sidebar reverts to its original width.
This perfectly matches your requirement of only applying the size change during the toggle operation.
内容的提问来源于stack exchange,提问作者RawalD

