如何覆盖CSS ::after选择器?移除指定外链:after图标方案
Hey there! Let’s break down your questions and solve them with practical examples based on your code.
1. General Approach to Override CSS ::after Selectors
To override a ::after pseudo-element style, you need to leverage CSS specificity (the priority of your selector) or adjust the order of your styles. Here’s how it works:
- Increase selector specificity: Use a more specific selector than the original (e.g., add a class, ID, or parent element to your target selector). Specificity ranks from highest to lowest:
!important> ID > class/attribute > element. - Order matters: If two selectors have the same specificity, the later style in your CSS will override the earlier one.
- Use
!importantsparingly: While it works, it can make your CSS harder to maintain. Only use it if you can’t modify the original selector structure.
2. Remove the External Icon for the "Hello2" Link (Without Changing Existing CSS)
Your existing CSS adds an icon to all a[target="_blank"] links. To remove it only for the "Hello2" link, follow these steps:
Step 1: Add a Custom Class to the Target Link
First, update your HTML to give the "Hello2" link a unique class (we’ll use no-external-icon here):
<a href="#" target="_blank">Hello1</a> <a class="no-external-icon" href="#" target="_blank">Hello2</a>
Step 2: Add Override CSS
Now, create a more specific selector to target just that link’s ::after pseudo-element and disable the icon. You have two simple options:
Option 1: Clear the content Property
This removes the icon and resets the margin to avoid extra space:
/* Keep your original CSS as-is */ a[target="_blank"]:after { content:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAQElEQVR42qXKwQkAIAxDUUdxtO6/RBQkQZvSi8I/pL4BoGw/XPkh4XigPmsUgh0626AjRsgxHTkUThsG2T/sIlzdTsp52kSS1wAAAABJRU5ErkJggg==); margin: 0 3px 0 5px; } /* Override for the specific link */ a.no-external-icon[target="_blank"]:after { content: ""; /* Empty content removes the icon */ margin: 0; /* Reset margin to eliminate extra spacing */ }
Option 2: Hide the Pseudo-Element
If you just want to hide it without adjusting spacing, use display: none:
/* Keep your original CSS as-is */ a[target="_blank"]:after { content:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAQElEQVR42qXKwQkAIAxDUUdxtO6/RBQkQZvSi8I/pL4BoGw/XPkh4XigPmsUgh0626AjRsgxHTkUThsG2T/sIlzdTsp52kSS1wAAAABJRU5ErkJggg==); margin: 0 3px 0 5px; } /* Override for the specific link */ a.no-external-icon[target="_blank"]:after { display: none; /* Completely hides the ::after element */ }
Why This Works
The selector a.no-external-icon[target="_blank"]:after has higher specificity than the original a[target="_blank"]:after (it includes an extra class selector). This means the override styles will take precedence, even though the original CSS remains intact.
内容的提问来源于stack exchange,提问作者bob mason

