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)