contain 属性
页面的渲染包含下面几个流程
图片来自 Inside a super fast CSS engine: Quantum CSS (aka Stylo)
页面元素的布局或样式发生变化时都有可能会引发 reflow 或 repaint,为了避免这种情况,提升浏览器性能。
CSS 新出了 contain
属性,拥有 contain
属性(不为 none
)的元素与页面其他元素相对独立,并且该元素及其后代元素样式、DOM 发生变化时不会导致整个页面回流和重绘。
语法
1 | contain: none | strict | content | [ size || layout || paint ] |
layout:元素内部的布局不会影响页面其他元素,反之也一样
- Any overflow is treated as ink overflow:元素的溢出并不会影响布局,溢出效果类似于
box-shadow
、text-decoration
- Containing block for absolute positioned、fixed positioned elements:元素后代的定位元素(
absolute
、fixed
)都是相对于元素自身进行定位的 - Create stacking context:会创建层叠上下文
- Establish Independent formatting context
- No baseline
- Any overflow is treated as ink overflow:元素的溢出并不会影响布局,溢出效果类似于
paint:溢出内容会被隐藏,效果类似于
overflow:hidden
- Contents are clipped
- Containing block for absolute positioned、fixed positioned elements
- Create stacking context
- Establish Independent formatting context
size:在计算元素容器大小时,元素内容会被忽略
- Treated as having no contents
counters and quotes cannot escape this element
contain: style
存在风险,暂为将其放入规范中
content:同时包含
content
、paint
、的效果style
strict:同时包含
layout
、content
、paint
、的效果style
扩展
IE 6~11、 Edge、Safari 均不支持该属性
contain
属性仅在display
属性值为block
、flex
、grid
等的元素上有效果If the element does not generate a principal box (as is the case with display values of contents or none), or its principal box is an internal table box other than table-cell, or an internal ruby box, or a non-atomic inline-level box, layout containment has no effect.
contain
性能测试