CSS中为id="outer"元素及其所有后代应用样式的简洁写法问询
Nice question—DRY (Don’t Repeat Yourself) is always a good goal in CSS! Let’s look at a few better alternatives to your original #outer, #outer * { border: medium solid; } approach.
1. 原生CSS: Use the :is() selector for cleaner selector logic
While it doesn’t save a ton of characters for a short selector like #outer, the :is() pseudo-class lets you avoid repeating the base selector—this becomes way more valuable if your base selector gets complex (e.g., .container#outer[data-theme="dark"]). Here’s how it works:
:is(#outer, #outer *) { border: medium solid; }
Now if you ever need to update the base selector (say, change #outer to .outer-container), you only have to edit it once instead of twice—true DRY behavior.
2. Leverage CSS inheritance (even better for style reuse)
Border properties don’t inherit by default, but you can explicitly set them to inherit on child elements. This way you only define the border style once on the parent, and all children pick it up automatically:
#outer { border: medium solid; } #outer * { border: inherit; }
This is super DRY because if you want to tweak the border (e.g., change medium solid to thin dashed red), you only modify one line of code instead of two. Perfect for consistent styling across a parent and its descendants.
3. CSS Preprocessors (SCSS/Sass, Less): Nesting + reuse patterns
If you’re using a preprocessor like SCSS, you can use nesting to avoid repeating the parent selector entirely, plus mixins or placeholder selectors to reuse the style declaration:
Option A: Basic nesting (reduces selector repetition)
#outer { border: medium solid; & * { border: medium solid; } }
Option B: Placeholder selector for true DRY style reuse
%border-base { border: medium solid; } #outer { @extend %border-base; & * { @extend %border-base; } }
Now you can reuse %border-base anywhere else in your stylesheet too, and updating the border style only requires changing one line.
Quick edge case note
Keep in mind that #outer * won’t match pseudo-elements like ::before or ::after—if you need those included, add them to your selector list (e.g., :is(#outer, #outer *, #outer ::before, #outer ::after)).
内容的提问来源于stack exchange,提问作者BeeOnRope

