CSS contain Property: What It Is and How It Works
contain property in CSS tells the browser to limit the scope of certain styles and layout calculations to an element and its contents only. This helps improve page performance by reducing unnecessary work outside that element.How It Works
Imagine you have a big room with many objects, and you only want to clean one corner without disturbing the rest. The contain property acts like a barrier that tells the browser to focus only on that corner (the element) when calculating styles, layout, or paint. This means changes inside that element won’t cause the browser to check or redraw other parts of the page.
By using contain, the browser can skip some expensive tasks outside the element, making the page faster and smoother. It works by limiting the element’s impact on the rest of the page in terms of size, layout, style, and paint.
Example
This example shows a box with contain: layout style; which tells the browser to contain layout and style calculations inside the box only.
html {
font-family: Arial, sans-serif;
}
.container {
width: 300px;
border: 2px solid #4CAF50;
padding: 10px;
contain: layout style;
}
.box {
width: 100%;
height: 100px;
background-color: #a8d5a2;
transition: background-color 0.3s ease;
}
.box:hover {
background-color: #6bbf59;
}When to Use
Use contain when you want to improve page speed by limiting how much the browser recalculates when something changes inside an element. It is especially helpful for complex components like widgets, modals, or cards that update often.
For example, if you have a chat box or a photo gallery that changes content dynamically, adding contain can prevent the whole page from re-layout or repaint, making interactions smoother.
Key Points
containlimits browser work to the element and its children.- It can contain layout, style, paint, and size calculations.
- Helps improve performance on complex or dynamic parts of a page.
- Use carefully, as it changes how elements interact with the rest of the page.
Key Takeaways
contain tells the browser to isolate an element’s layout and style work.contain to make your page smoother and faster.