类选择器中的伪元素无法正常工作,寻求解决办法
It’s super frustrating when pseudo-elements behave differently between ID and class selectors—let’s break down the most common reasons this happens and how to fix them.
1. You’re Missing the content Property
Pseudo-elements (::before/::after) require the content property to render, even if it’s empty. If you forgot this line for your class selector, the arrow won’t show up at all. This is one of the easiest mistakes to overlook!
Example Fix:
.correct::after { content: ''; /* Don’t skip this! */ position: absolute; right: -15px; top: 50%; transform: translateY(-50%); /* Arrow shape styles */ border-left: 12px solid green; border-top: 8px solid transparent; border-bottom: 8px solid transparent; }
2. Specificity Is Overriding Your Class Rule
ID selectors have way higher specificity than class selectors. If there’s an ID-based pseudo-element rule targeting the same element, it will completely override your class-based styles.
How to Fix:
Boost the specificity of your class selector. For example, combine it with a parent class or element:
.question-container .correct::after { /* Your arrow styles here */ }
Or use !important sparingly (only if necessary, since it can make future debugging harder):
.correct::after { content: ''; border-left-color: green !important; /* Other arrow styles */ }
3. The Class Isn’t Properly Applied to the Div
Double-check your HTML to make sure the class is actually assigned to the div. A tiny typo (like corret instead of correct) or forgetting to add the class entirely will stop the styles from applying.
Example Correct HTML:
<div class="correct">This div should have a side arrow</div>
4. Missing Positioning Setup
To position an arrow outside the div, you need to set the parent div to position: relative and the pseudo-element to position: absolute. Without this, the arrow might be hidden or stuck inside the div’s bounds.
Full Working Example:
.correct { background-color: green; color: white; padding: 12px; position: relative; /* Required for absolute positioning of pseudo-element */ } .correct::after { content: ''; position: absolute; right: -20px; /* Push arrow outside the div */ top: 50%; transform: translateY(-50%); /* Arrow shape */ border-left: 15px solid green; border-top: 10px solid transparent; border-bottom: 10px solid transparent; }
5. Parent Element Is Hiding the Arrow
If the parent of your div has overflow: hidden, it will clip any content (including pseudo-elements) that goes outside its edges. Check parent styles and adjust if needed:
.parent-wrapper { overflow: visible; /* Replace hidden with visible */ }
Go through these steps one by one—chances are it’s one of these common issues causing your class-based pseudo-element to not show up.
内容的提问来源于stack exchange,提问作者namo

