0
0
CSSmarkup~8 mins

Before pseudo-element in CSS - Performance & Optimization

Choose your learning style9 modes available
Performance: Before pseudo-element
MEDIUM IMPACT
This affects the rendering performance by adding extra elements to the DOM visually, which can increase paint and composite work.
Adding decorative content before an element without extra HTML
CSS
p::before { content: ''; display: inline-block; width: 200px; height: 200px; background-image: url('small-icon.svg'); background-size: contain; background-repeat: no-repeat; }
Using a small SVG as background with fixed size reduces paint cost and prevents layout shifts.
📈 Performance Gainsingle paint, stable layout, reduced CLS
Adding decorative content before an element without extra HTML
CSS
p::before { content: url('large-image.png'); display: inline-block; width: 200px; height: 200px; }
Using a large image in ::before increases paint cost and can cause layout shifts if dimensions are not reserved properly.
📉 Performance Costtriggers multiple paints and can cause CLS if size is not fixed
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Large image in ::beforeNo extra DOM nodes, but visual layer added1 reflow if size not fixedHigh paint cost due to large image[X] Bad
Small SVG background in ::beforeNo extra DOM nodes, visual layer addedNo reflow with fixed sizeLow paint cost with vector image[OK] Good
Rendering Pipeline
The ::before pseudo-element is generated during style calculation and layout stages, adding a visual layer before the element's content. It requires paint and composite steps to render the added content.
Style Calculation
Layout
Paint
Composite
⚠️ BottleneckPaint
Core Web Vital Affected
CLS
This affects the rendering performance by adding extra elements to the DOM visually, which can increase paint and composite work.
Optimization Tips
1Avoid large images in ::before to reduce paint cost.
2Always set fixed width and height on ::before to prevent layout shifts.
3Use simple content like text or small SVG backgrounds for better performance.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a common performance issue when using large images in ::before pseudo-elements?
AIncreased paint cost and possible layout shifts
BIncreased JavaScript execution time
CMore HTTP requests for HTML files
DSlower CSS selector matching
DevTools: Performance
How to check: Record a performance profile while loading the page and inspect the paint and composite events related to the element with ::before.
What to look for: Look for long paint times or layout shifts caused by the pseudo-element to identify performance issues.