You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C#中为所有CSS选择器添加#ID前缀的实现求助

How to Add a Specific ID Prefix to CSS Selectors in C#

Got it, I’ve been in similar spots where I needed to scope CSS to a specific container without rewriting the whole stylesheet. Here’s a straightforward way to prepend your target ID prefix to each selector in your CSS string using C#:

Step-by-Step Solution

We’ll use regular expressions to match each CSS selector line and insert the ID prefix. This works perfectly for your example of element selectors (body, header, etc.), and can be adjusted if you have more complex selectors later.

Example Code

using System.Text.RegularExpressions;

// Your original CSS string
string originalCss = @"body { color: white; background-color: #aaaaaa } 
header { color: blue; background-color: #bbbbbb } 
main { color: red; background-color: #cccccc } 
footer { color: green; background-color: #dddddd }";

// Define your target ID prefix
string idPrefix = "#someID";

// Use regex to prepend the prefix to each selector
string modifiedCss = Regex.Replace(
    originalCss,
    @"(^\s*)([\w-]+)(\s*{)",
    $"$1{idPrefix} $2$3",
    RegexOptions.Multiline
);

What This Does

  • The RegexOptions.Multiline flag lets the ^ character match the start of every line (not just the start of the entire string).
  • The regex breaks down each line into three groups:
    1. (^\s*): Captures any leading whitespace before the selector (so we preserve original formatting).
    2. ([\w-]+): Matches the selector itself (works for element names, class names, and IDs with hyphens).
    3. (\s*{): Captures whitespace before the opening brace and the brace itself.
  • The replacement string inserts your ID prefix between the leading whitespace and the selector, keeping everything formatted as it was.

Result

The modified CSS will look exactly like what you need:

#someID body { color: white; background-color: #aaaaaa } 
#someID header { color: blue; background-color: #bbbbbb } 
#someID main { color: red; background-color: #cccccc } 
#someID footer { color: green; background-color: #dddddd }

Notes for More Complex CSS

If your stylesheet includes combinators (like div p), nested selectors, or pseudo-classes, you can tweak the regex to handle those. For example, to match selectors that might have spaces or other characters, you could use a more flexible pattern like @"(^\s*)([^}]+?)(\s*{)" — just be aware this might need additional refinement based on your specific CSS structure.

内容的提问来源于stack exchange,提问作者Carlos Miranda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:31:52