CSS 新特性 contain,控制页面重获新生

发现之前已经描述过很多次了,可以看看这个提高 CSS 动画性能的正确姿势[1]

OK,下面进入本文正题,

contain 为何?

contain 属性允许我们指定特定的 DOM 元素和它的子元素,让它们能够独立于整个 DOM 树结构之外。目的是能够让浏览器有能力只对部分元素进行重绘、重排,而不必每次都针对整个页面。

  • The contain property allows an author to indicate that an element and its contents are, as much as possible, independent of the rest of the document tree. This allows the browser to recalculate layout, style, paint, size, or any combination of them for a limited area of the DOM and not the entire page.

contain 语法

看看它的语法:


  1.   /* No layout containment. */ 
  2.   contain: none; 
  3.   /* Turn on containment for layout, style, paint, and size. */ 
  4.   contain: strict; 
  5.   /* Turn on containment for layout, style, and paint. */ 
  6.   contain: content; 
  7.   /* Turn on size containment for an element. */ 
  8.   contain: size
  9.   /* Turn on layout containment for an element. */ 
  10.   contain: layout; 
  11.   /* Turn on style containment for an element. */ 
  12.   contain: style; 
  13.   /* Turn on paint containment for an element. */ 
  14.   contain: paint; 

除去 none,取值还有 6 个,我们一个一个来看看。

contain: size

contain: size: 设定了 contain: size 的元素的渲染不会受到其子元素内容的影响。

  • The value turns on size containment for the element. This ensures that the containing box can be laid out without needing to examine its descendants.

我开始看到这个定义也是一头雾水,光看定义很难明白到底是什么意思。还需实践一番:

假设我们有如下简单结构:


  1. <div class="container"
  2.     
  3. </div> 

  1. .container { 
  2.     width: 300px; 
  3.     padding: 10px; 
  4.     border: 1px solid red; 
  5.  
  6. p { 
  7.     border: 1px solid #333; 
  8.     margin: 5px; 
  9.     font-size: 14px; 

并且,借助 jQuery 实现每次点击容器添加一个 <p>Coco</p> 结构:


  1. $('.container').on('click', e => { 
  2.     $('.container').append('<p>Coco</p>'
  3. }) 

那么会得到如下结果:

【声明】:芜湖站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

相关文章