You might have experienced lag when scrolling through a website. While it’s easy to blame JavaScript for performance
issues, CSS can also play a significant role—especially with elements that use position: fixed
or apply heavy styles
like box shadows.
A common culprit is the fixed navigation bar, particularly the top navbar. This element, if not optimized, can lead to frequent repaints and sluggish scroll performance.
#Diagnosing the problem
To detect these performance issues, you can use Chrome DevTools. Open DevTools, press Esc
to bring up the console, and
navigate to the Rendering tab to enable paint flashing.
As you scroll, green blocks will appear, indicating areas that are being repainted. Repaints are resource-intensive and are often the reason for a laggy experience.
Here’s an example of what that looks like:
#Minimizing repaints
If your navbar or other elements are causing frequent repaints, a simple CSS trick can help. Add the following rule to your position: fixed element:
This creates a new layer for the element, reducing the number of repaints and boosting scroll performance by about 5-10 frames per second.
#Why this works
The will-change
property optimizes how the browser handles the element, similar to the older
transform: translateZ(0)
trick, but in a more targeted way. It tells the browser to prepare for changes to the
transform property, reducing the overhead caused by scrolling.
#Use with caution
While this can provide an immediate performance boost, overusing will-change can lead to excessive memory consumption. Use it only where necessary to avoid trade-offs in other areas of your site’s performance.