DEV Community

Cover image for Why contain in CSS Can Fix Your Performance Bottlenecks
Pawar Shivam
Pawar Shivam

Posted on

Why contain in CSS Can Fix Your Performance Bottlenecks

=> What If Components Didn’t Affect Each Other?

Normally in CSS:

πŸ‘‰ one element can affect the whole layout
πŸ‘‰ browser recalculates everything

This slows down rendering.


=> The Hidden CSS Optimization

.card {
  contain: layout paint;
}
Enter fullscreen mode Exit fullscreen mode

Now the browser treats it like:

πŸ‘‰ an isolated component
πŸ‘‰ no outside impact


=> What contain Actually Does

It limits:

  • layout calculations
  • paint rendering
  • size reflows

=> Different Types of Containment

.box {
  contain: layout;
  contain: paint;
  contain: size;
  contain: style;
}
Enter fullscreen mode Exit fullscreen mode

Or all together:

.box {
  contain: strict;
}
Enter fullscreen mode Exit fullscreen mode

=> Why This Improves Performance

Without contain:

πŸ‘‰ changes trigger global recalculation

With contain:

πŸ‘‰ only local area updates


=> Real Use Case

.card {
  contain: content;
}
Enter fullscreen mode Exit fullscreen mode

Perfect for:

  • cards
  • widgets
  • dashboards

=> What Developers Often Miss

Modern performance is not just:

πŸ‘‰ lazy loading
πŸ‘‰ image optimization

It’s also:

πŸ‘‰ rendering isolation


=> Warning

If used incorrectly:

πŸ‘‰ layout can break
πŸ‘‰ size calculations may fail


=> Real UI Tip

Use contain when:

πŸ‘‰ component is independent
πŸ‘‰ layout doesn’t depend on outside


=> What Do You Think?

Would you use CSS contain instead of optimizing everything manually?

Top comments (0)