如何通过C#后台代码动态添加伪元素行内CSS?
Hey there! Let's work through your problem. First, a quick heads-up: you can't add pseudo-element styles (like ::after) directly via inline CSS—the style attribute only applies styles to the element itself, not its pseudo-children. But we can still achieve your desired hover animation by dynamically injecting the necessary CSS rules from your C# backend. Here's how:
Step 1: Understand the Animation Logic
We want the full category name to appear when hovering over the initial character. We'll use the ::after pseudo-element to hold the rest of the text (" ECHNOLOGY"), hide it by default, and fade it in on hover with a smooth transition.
Step 2: Inject CSS Dynamically from C#
Option 1: ASP.NET WebForms
In your code-behind (e.g., YourPage.aspx.cs), add this to the Page_Load event to insert a <style> block into the page's <head>:
protected void Page_Load(object sender, EventArgs e) { // Create a new style control HtmlGenericControl styleBlock = new HtmlGenericControl("style"); // Define the CSS rules for the hover effect styleBlock.InnerHtml = @".slide .btn_six::after { content: ' ECHNOLOGY'; opacity: 0; transition: opacity 0.3s ease-in-out; } .slide .btn_six:hover::after { opacity: 1; }"; // Add the style block to the page's head section Page.Header.Controls.Add(styleBlock); }
Option 2: ASP.NET Core/MVC (Razor)
In your controller, pass the CSS rules to the view via ViewBag or a view model:
public IActionResult YourAction() { ViewBag.CategoryHoverStyle = @".slide .btn_six::after { content: ' ECHNOLOGY'; opacity: 0; transition: opacity 0.3s ease-in-out; } .slide .btn_six:hover::after { opacity: 1; }"; return View(); }
Then in your Razor view's <head> section, render the style:
<style> @ViewBag.CategoryHoverStyle </style>
Step 3: Keep Your Existing HTML
Your original HTML doesn't need any changes—this CSS will target the existing btn_six class:
<div class="slide"> <a target="_blank" href="#" class="post-badge btn_six">T</a> </div>
How It Works
- The
::afterpseudo-element adds the remaining text " ECHNOLOGY" right after the "T". - We set
opacity: 0to hide it by default, and add atransitionfor smooth animation. - On
hover, we switchopacity: 1to make the full text visible.
This approach gives you the dynamic control you need from C# while working within CSS's limitations for pseudo-elements.
内容的提问来源于stack exchange,提问作者Learning

