1. Introduction
Efficiently rendering a website relies on the user agent being able to detect what parts of the page are being displayed, which parts might affect the currently-displayed section, and what can be ignored.
There are various heuristics that can be used to guess when a given sub-tree is independent of the rest of the page in some manner, but they’re fragile, so innocuous changes to a page may inadvertently make it fail such heuristic tests, causing rendering to fall into a slow code path. There are also many things that would be good to isolate which are difficult or impossible to detect in a heuristic manner.
To alleviate these problems and allow strong, predictable isolation of a subtree from the rest of the page, this specification defines a contain property.
To allow even further optimization of off-screen contents, this spec also defines a content-visibility property, enabling the user agent to skip an element’s layout and painting entirely when not needed.
1.1. Module Interactions
This document defines new features not present in earlier specifications. In addition, it aims to replace and supersede [CSS-CONTAIN-1] once stable.
1.2. Value Definitions
This specification follows the CSS property definition conventions from [CSS2] using the value definition syntax from [CSS-VALUES-3]. Value types not defined in this specification are defined in CSS Values & Units [CSS-VALUES-3]. Combination with other CSS modules may expand the definitions of these value types.
In addition to the property-specific values listed in their definitions, all properties defined in this specification also accept the CSS-wide keywords as their property value. For readability they have not been repeated explicitly.
2. Strong Containment: the contain property
Name: | contain |
---|---|
Value: | none | strict | content | [ size || layout || style || paint ] |
Initial: | none |
Applies to: | See below |
Inherited: | no |
Percentages: | n/a |
Computed value: | the keyword none or one or more of size, layout, paint |
Canonical order: | per grammar |
Animation type: | not animatable |
User agents are expected to support this property on all media, including non-visual ones.
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 user agents to utilize much stronger optimizations when rendering a page using contain properly, and allows authors to be confident that their page won’t accidentally fall into a slow code path due to an innocuous change.
- none
- This value indicates that the property has no effect. The element renders as normal, with no containment effects applied.
- strict
- This value computes to size layout paint style, and thus turns on all forms of containment for the element.
- content
-
This value computes to layout paint style,
and thus turns on all forms of containment except size containment for the element.
Note: contain: content is reasonably "safe" to apply widely; its effects are fairly minor in practice, and most content won’t run afoul of its restrictions. However, because it doesn’t apply size containment, the element can still respond to the size of its contents, which can cause layout-invalidation to percolate further up the tree than desired. Use contain: strict when possible, to gain as much containment as you can.
- size
- The value turns on size containment for the element. This ensures that the containment box can be laid out without needing to examine its descendants.
- layout
- This value turns on layout containment for the element. This ensures that the containment box is totally opaque for layout purposes; nothing outside can affect its internal layout, and vice versa.
- style
- This value turns on style containment for the element. This ensures that, for properties which can have effects on more than just an element and its descendants, those effects don’t escape the element.
- paint
- This value turns on paint containment for the element. This ensures that the descendants of the containment box don’t display outside its bounds, so if an element is off-screen or otherwise not visible, its descendants are also guaranteed to be not visible.
This property generally applies to all elements (including CSS Pseudo-Elements 4 § 4.1 Generated Content Pseudo-elements: ::before and ::after),
although some types of containment have no effect on some elements,
as detailed in § 3 Types of Containment.
In addition, in the case of [SVG2],
the contain property only applies to svg
elements that have an associated CSS layout box.
For example, assume a micropost social network had markup something like this:
< body >
< aside > ...</ aside >
< section >
< h2 > Messages</ h2 >
< article >
Lol, check out this dog: images.example.com/jsK3jkl
</ article >
< article >
I had a ham sandwich today. #goodtimes
</ article >
< article >
I have political opinions that you need to hear!
</ article >
…
</ section >
</ body >
There are probably a lot of messages displayed on the site, but each is independent and won’t affect anything else on the site. As such, each can be marked with contain: content to communicate this to the user agent, so it can optimize the page and skip a lot of computation for messages that are off-screen. If the size of each message is known ahead of time, contain: strict can be applied to communicate further restrictions.
Additionally, when any containments are active
on either the HTML html
or body
elements,
propagation of properties
from the body
element
to the initial containing block, the viewport, or the canvas background,
is disabled.
Notably, this affects:
-
writing-mode, direction, and text-orientation (see CSS Writing Modes 3 § 8 The Principal Writing Mode)
-
overflow and its longhands (see CSS Overflow 3 § 3.5 Overflow Viewport Propagation)
-
background and its longhands (see CSS Backgrounds 3 § 2.11.2 The Canvas Background and the HTML <body> Element)
Note: Propagation
to the initial containing block, the viewport, or the canvas background,
of properties set on the html
element itself
is unaffected.
Note: Several properties beyond contain can turn on various containments for an element. These do not affect the value of contain; an element can have contain: none but still have layout containment turned on by content-visibility, for example.
3. Types of Containment
There are several varieties of containment that an element can be subject to, restricting the effects that its descendants can have on the rest of the page in various ways. Containment enables much more powerful optimizations by user agents, and helps authors compose their page out of functional units, as it limits how widely a given change can affect a document.
Specification authors introducing new properties or mechanisms need to consider whether and how the various types of containment affect what they are introducing, and include in their specification any effect not described here.
3.1. Size Containment
Giving an element size containment makes its principal box a size containment box and has the following effects:
-
The intrinsic sizes of the size containment box are determined as if the element had no content, following the same logic as when sizing as if empty.
Note: This affects explicit invocations of the min-content or max-content keywords, as well as any calculation that depends on these measurement, such as sizing grid tracks into which a size contained item is placed, or if fit-content sizing the containment box’s parent.
-
Laying out a size containment box and its content is conceptually done in two phases:
- Sizing as if empty
-
The used width and height of the containment box are determined as if performing a normal layout of the box,
except that it is treated as having no content—
not even through pseudo elements such as ::before, ::after, or ::marker. Replaced elements must be treated as having an natural width and height of 0 and no natural aspect ratio.
Note: Size containment only suppresses the natural aspect ratio, so properties like aspect-ratio which affect that preferred aspect ratio directly are honored.
All CSS properties of the size containment box are taken into account as they would be when performing layout normally. Other specifications may make specific exemptions.
Note: Even when the element’s sizing properties specify an intrinsic size, this does not necessarily make the element zero-sized: properties set on the element itself continue to be taken into account, which can cause it to be larger.
- Laying out in-place
- The containment box's content (including any pseudo-elements) must then be laid out into the now fixed-size containment box normally.
Note: Size containment does not suppress baseline alignment. See layout containment for that.
-
Size containment boxes are monolithic (See CSS Fragmentation 3 § 4.1 Possible Break Points).
img
{ width : 100 px ; aspect-ratio : 1 /1 ; contain : size; }
< img src = "https://www.example.com/300x100.jpg" >
If the aspect-ratio property had not been declared, the image would have been 100px by 0px, as its natural aspect ratio is suppressed, and its natural height is treated as 0.
However, giving an element size containment has no effect if any of the following are true:
-
if the element does not generate a principal box (as is the case with display: contents or display: none)
-
if its inner display type is table
-
if its principal box is an internal table box
-
if its principal box is an internal ruby box or a non-atomic inline-level box
Note: Internal table boxes, which do not include table captions, are excluded, because the table layout algorithm does not allow boxes to become smaller than their inflow content. Sizing a table cell as if it was empty and then laying out its content inside without changing the size is effectively an undefined operation. Manually setting the width or height properties to 0 cannot make it smaller than its content. This concern does not apply to table captions, which are perfectly capable of having a fixed size that is independent of their content.
3.1.1. Possible Size-Containment Optimizations
This section is non-normative.
By itself, size containment does not offer much optimization opportunity. Its primary benefit on its own is that tools which want to lay out the containment box's contents based on the containment box's size (such as a JS library implementing the "container query" concept) can do so without fear of "infinite loops", where having a child’s size respond to the size of the containment box causes the containment box's size to change as well, possibly triggering further changes in how the child sizes itself and possibly thus more changes to the containment box's size, ad infinitum.
When paired with layout containment, though, possible optimizations that can be enabled include (but are not limited to):
-
When the style or contents of a descendant of the containment box is changed, calculating what part of the DOM tree is "dirtied" and might need to be re-laid out can stop at the containment box.
-
When laying out the page, if the containment box is off-screen or obscured, the layout of its contents (i.e. "laying out in-place") can be delayed or done at a lower priority.
3.2. Layout Containment
Giving an element layout containment makes its principal box a layout containment box and has the following effects:
-
The layout containment box establishes an independent formatting context.
-
If at least one fragmentation container of a fragmentation context has layout containment, or if at least one fragmentation container of a fragmentation context is a descendant of layout containment box and at least one subsequent fragmentation container of the same fragmentation context is not a descendant of that same element with layout containment, then the first layout containment box which is either a fragmentation container itself or is an ancestor of a fragmentation container must “trap” the remainder of the fragmented flow: fragmentation must not continue past the layout containment boundary, and the last fragmentation container within the first layout containment boundary is treated as if it is the last fragmentation container in its fragmentation context.
If subsequent fragmentation containers in the fragmentation context are only generated when more content remains in the fragmented flow, then they are not generated. If they would exist regardless, they remain part of the fragmentation context, but do not receive any content from the fragmented flow.
Note: At the time of writing, no stable specification is affected by this point. Only specifications that would enable some (but not all) fragmentation containers of a fragmentation context to be layout-contained (or descendants of a layout contained element) are concerned. This is not the case of [CSS-PAGE-3] nor of [CSS-MULTICOL-1]. This requirement is nonetheless included because several mechanisms that would make this a possibility have been considered (e.g.: [CSS-REGIONS-1], ::nth-fragment(), a hypothetical selector for individual columns of a multicol…), and the guarantees that layout containment is intended to offer would not be realized if such mechanisms did not abide by this rule. [CSS-REGIONS-1] has details over how layout containment affects regions.
< article > Lorem ipsum…</ article > < div id = a ></ div > < aside > < div id = b ></ div > < div id = c ></ div > </ aside > < aside > < div id = d ></ div > < div id = e ></ div > </ aside > < div id = f ></ div > article
{ flow-into : foo;} #a, #b, #c, #d, #e, #f{ flow-from : foo;} aside{ contain : layout} In this [CSS-REGIONS-1] example, content can flow from
#a
to#b
, from#b
to#c
. However as#c
is the last fragment container in the first layout containment box it traps all the remaining content, and nothing gets flowed into#d
,#e
, or#f
. -
If the computed value of the overflow property is either visible or clip or a combination thereof, any overflow must be treated as ink overflow.
-
The layout containment box establishes an absolute positioning containing block and a fixed positioning containing block.
-
The layout containment box creates a stacking context.
-
Forced breaks are allowed within layout containment boxes but do not propagate to the parent as otherwise described in CSS Fragmentation 3 § 3.1 Breaks Between Boxes: the break-before and break-after properties.
Note: This introduces the previously non-existent possibility that forced breaks may occur between a box and its container (See CSS Fragmentation 3 § 4.1 Possible Break Points).
-
For the purpose of the vertical-align property, or any other property whose effects need to relate the position of the layout containment box's baseline to something other than its descendants, the containment box is treated as having no baseline.
However, giving an element layout containment has no effect if any of the following are true:
-
if the element does not generate a principal box (as is the case with display: contents or display: none)
-
if its principal box is an internal table box other than table-cell
-
if its principal box is an internal ruby box or a non-atomic inline-level box
3.2.1. Possible Layout-Containment Optimizations
This section is non-normative.
Possible optimizations that can be enabled by layout containment include (but are not limited to):
-
When laying out the page, the contents of separate containment boxes can be laid out in parallel, as they’re guaranteed not to affect each other.
-
When laying out the page, if the containment box is off-screen or obscured and the layout of the visible parts of the screen do not depend on the size of the containment box (for example, if the containment box is near the end of a block container, and you’re viewing the beginning of the block container), the layout of the containment box' contents can be delayed or done at a lower priority.
(When paired with size containment, this optimization can be applied more liberally.)
3.3. Style Containment
Giving an element style containment has the following effects:
-
The counter-increment and counter-set properties must be scoped to the element’s sub-tree and create a new counter.
-
The effects of the content property’s open-quote, close-quote, no-open-quote and no-close-quote must be scoped to the element’s sub-tree.
Note: This implies that the depth of quote nesting in the subtree is unchanged and starts at the value that its context normally implies, but that changes to the depth of quote nesting by these values inside the subtree do not affect the depth of quote nesting outside the subtree.
Note: [CSS-REGIONS-1] has normative requirements on how style containment affects regions.
A scoped property has its effects scoped to a particular element or subtree.
-
If scoped to an element, it must act as if the scoping element was the root of the document for the purpose of evaluating the property’s effects: any uses of the property outside the scoping element must have no effect on the uses of the property on or in the scoping element, and vice versa.
Note: “Scoping to an element” is currently unused. It is defined as an extension point for future specifications to use.
-
If scoped to a sub-tree, it’s the same, except the scoping element itself is counted as "outside" the tree, like the rest of the document, and the effects of the property on that element are unaffected by scoping. When considering the effects of the scoped property on elements inside the subtree, the element at the base of the subtree is treated as if it was the root of the document.
1 1.2being displayed:
< div ></ div >
div {
contain : style;
counter-increment : n;
}
div::before, div::after {
content : counters ( n, '.' ) " " ;
}
div::after {
counter-increment : n 2 ;
}
3.3.1. Possible Style-Containment Optimizations
This section is non-normative.
Possible optimizations that can be enabled by style containment include (but are not limited to):
-
Whenever a property is changed on a descendant of an element with style containment, calculating what part of the DOM tree is "dirtied" and might need to have its style recalculated can stop at the element with style containment.
3.4. Paint Containment
Giving an element paint containment makes its principal box a paint containment box and has the following effects:
-
The contents of the element including any ink or scrollable overflow must be clipped to the overflow clip edge of the paint containment box, taking [[css-backgrounds-3#corner clipping|corner clipping]] into account. This does not include the creation of any mechanism to access or indicate the presence of the clipped content; nor does it inhibit the creation of any such mechanism through other properties, such as overflow, resize, or text-overflow.
Note: This clipping shape respects overflow-clip-margin, allowing an element with paint containment to still slightly overflow its normal bounds.
Note: The behavior is described in this paragraph is equivalent to changing overflow-x: visible into overflow-x: clip and overflow-y: visible into overflow-y: clip at used value time, while leaving other values of overflow-x and overflow-y unchanged.
-
The paint containment box establishes an absolute positioning containing block and a fixed positioning containing block.
-
The paint containment box creates a stacking context.
-
The paint containment box establishes an independent formatting context.
However, giving an element paint containment has no effect if any of the following are true:
-
if the element does not generate a principal box (as is the case with display: contents or display: none)
-
if its principal box is an internal table box other than table-cell
-
if its principal box is an internal ruby box or a non-atomic inline-level box
3.4.1. Possible Paint-Containment Optimizations
This section is non-normative.
Possible optimizations that can be enabled by paint containment include (but are not limited to):
-
If the containment box is off-screen or obscured, the UA can usually skip trying to paint its contents, as they’re guaranteed to be off-screen/obscured as well.
Note: Some paint effects such as the blur() filter from [FILTER-EFFECTS-1] have non local effects. The user agent needs to keep track of these, as it may need to repaint parts of an element with such a filter when its descendents change, even if they have paint containment and could otherwise be skipped.
-
Unless the clipped content is made accessible via a separate mechanism such as the overflow, resize, or text-overflow properties, the UA can reserve "canvas" space for the box exactly the box’s size. (In similar, scrollable, situations, like overflow: hidden, it’s possible to scroll to the currently-clipped content, so UAs often predictively overpaint somewhat so there’s something to see as soon as the scroll happens, rather than a frame later.)
-
Because they are guaranteed to be stacking contexts, scrolling elements can be painted into a single GPU layer.
4. Suppressing An Element’s Contents Entirely: the content-visibility property
Name: | content-visibility |
---|---|
Value: | visible | auto | hidden |
Initial: | visible |
Applies to: | elements for which layout containment can apply |
Inherited: | no |
Percentages: | n/a |
Computed value: | as specified |
Canonical order: | per grammar |
Animation type: | not animatable |
The content-visibility property controls whether or not an element renders its contents at all, along with forcing a strong set of containments, allowing user agents to potentially omit large swathes of layout and rendering work until it becomes needed. It has the following values:
- visible
-
No effect. The element’s contents are laid out and rendered as normal.
- hidden
-
The element skips its contents.
The skipped contents must not be accessible to user-agent features, such as find-in-page, tab-order navigation, etc., nor be selectable or focusable.
Note: This is similar to giving the contents display: none.
- auto
-
Turns on layout containment, style containment, and paint containment for the element.
If the element is not relevant to the user, it also skips its contents.
Unlike skipped contents must still be available as normal to user-agent features such as find-in-page, tab order navigation, etc., and must be focusable and selectable as normal.
, the
The user agent should additionally avoid as much layout/rendering work as possible for skipped contents; the combination of heavy containment and making the contents invisible and untouchable enables heavy optimizations. If rendering work is done at some point, the user-agent should retain the previously computed layout state if possible, to allow the skipped contents to be displayed quickly at a later moment.
-
layout containment ensures that the user-agent is able to omit layout work in skipped subtrees, since the results of such layouts will not affect elements outside of the container element.
-
style containment ensures that counters do not have to be processed in skipped subtrees, since they do not affect counters outside of the container element.
-
paint containment ensures that ink overflow of painted contents is clipped; this, in turn, means that user-agent can reliably determine when the visible portion of the element approaches the viewport (and, for content-visibility: auto, start painting it).
-
size containment ensures that the user-agent is able to omit layout in skipped subtrees, since the results of such layouts will not affect the container element’s size.
Note that in the content-visibility: auto case, layout containment, style containment, and paint containment persist even if the element is not skipped. This is done to prevent layout changes that would be incurred by containment changes as a result of an element entering and exiting the skipped state.
-
The element is "on-screen": its paint containment box's overflow clip edge intersects with the viewport, or a user-agent defined margin around the viewport.
Note: This margin is meant to allow the user agent to begin preparing for an element to be in the viewport soon. A margin of 50% is suggested as a reasonable default.
-
Either the element or its contents are focused, as described in the focus section of the HTML spec.
-
Either the element or its contents are selected, as described in CSS Pseudo-Elements 4 § 3 Highlight Pseudo-elements.
-
Either the element or its contents are placed in the top layer.
4.1. Using content-visibility: hidden
This section is non-normative.
content-visibility: hidden lays powerful restrictions onto an element, and so should be used with caution. It also enables some very useful scenarios, often improving on existing techniques, a few of which are outlined here.
-
If a page needs to take some measurements of elements or text which aren’t themselves going to be rendered, commonly this is done by positioning the stuff-to-be-measured off-screen, using something like position: absolute; left: -100000px;, then calling an API like
getBoundingClientRect()
.Unfortunately, even though the page never intends to display this content, the user agent will still have to do full styling, layout, and rendering for the content, just in case it affects what’s shown on screen. The author also can’t, without further work, guarantee that the content won’t accidentally show up on-screen; even a very negative left value (like above) might not be enough, depending on the content.
Wrapping this content in a content-visibility: hidden container solves all of these problems. If the wrapper has no border, background, etc, then it and its skipped contents are guaranteed to never render anything to the screen, no matter how big they get. Because the contents are skipped, the user agent can also avoid styling or laying them out until absolutely necessary, when script finally asks for it.
-
A "single-page app" often consists of several independent panes or "views", of which only one is displayed at a time.
If the author wants to avoid paying styling/layout/rendering/etc cost for the inactive views, they can remove them from the document entirely, or at minimum apply display:none to them. Unfortunately, this means that when the view does need to be displayed, all of the styling/layout/rendering/etc work needs to be done all at once, potentially causing a noticeable delay before the view actually shows up.
Alternately, the view can just be positioned off-screen. This means it’ll be immediately ready when it’s time to be used, but it incurs the cost of styling/layout/rendering all the time, which might be significant, especially if there are a number of inactive views. The inactive views also might still show up to accessibility tooling, confusing users of screen-readers, people using Ctrl-F to find-in-page, etc.
content-visibility: hidden improves on both of these options. Because the contents are skipped, the user agent isn’t spending time on them when they’re not active. They’re also not visible to screen readers, find-in-page, and other tools. And because user agents should preserve previous styling/layout work if possible, if the view was displayed before, re-rendering it might be very fast.
-
If an author wants to make an element "invisible", but still show up in the page for layout purposes, one option is visibility: hidden. However, descendants of a visibility: hidden element can set visibility: visible and start showing up again, which isn’t always intuitive or expected.
content-visibility: hidden performs a very similar purpose, but descendants can’t turn it "off" and start displaying; they stay "hidden" until the ancestor turns it off.
Because content-visibility: hidden also applies many containment values to the container, it’s not always quite as usable as visibility: hidden would be, but when its restrictions are acceptable, it can be a more reliable, more consistent way to hide an element’s contents.
4.2. Using content-visibility: auto
This section is non-normative.
content-visibility: auto is a more complex value than ; rather than being similar to display: none, it adaptively hides/displays an element’s contents as they become relevant to the user. It also doesn’t hide its skipped contents from the user agent, so screen readers, find-in-page, and other tools can still interact with it.
It is best to think of it as an upgrade to containment: if an author has a large amount of content to display that will often be off-screen (such as a long scrollable list), and that content is okay with heavy containment, they should consider using content-visibility: auto to apply all of the containments at once. This also strongly hints to the user agent that it’s acceptable to skip work on the contents (possibly causing a small delay when they do come on-screen) because it’s more important to have a large amount of content in the document and most of it won’t be seen anyway.
Note: content-visibility: auto can thus be used instead of complicated "virtual list" techniques, at least in many cases.
Because content-visibility: auto only causes the element to skip its contents when none of it is relevant to the user, it’s best to use at a reasonably fine granularity.
Instead, content-visibility should be applied to individual tweets, allowing each of them to be skipped as they go off-screen.
Because content-visibility: auto imposes size containment when the element skips its contents, if the element depends on its contents to determine its size the layout of the page (or at least, the scrollbar position) can "jump around" as elements go off-screen and start skipping.
-
making the element fixed-size
-
carefully arranging a layout such as Grid to size the element without depending on its contents
-
using contain-intrinsic-size to set an estimate of the element’s size
-
using contain-intrinsic-size: auto to automatically "snapshot" the exact size of the element from the last time it was rendered, before it was skipped (along with providing an estimate of the size to be used before it’s rendered and can have its size snapshotted)
For example, on Twitter, the average tweet is approximately 200px tall, so contain-intrinsic-size: auto 500px 200px will ensure that the scrollbar thumb is in approximately the correct size and position even when preceding or following tweets are skipped, while still allowing the tweets to size according to their contents when they’re on-screen. As long as the tweets have all been viewed at least once (and haven’t changed size while they were skipped), their sizes will be exactly correct while they’re skipped, so the scrollbar thumb will be as well; only freshly-loaded tweets (such as those loaded at the top of the timeline while you are scrolling further down) will be forced to rely on the 200px height estimate.
4.3. Detecting content-visibility: auto state changes: the contentvisibilityautostatechanged event
The contentvisibilityautostatechanged
event is fired on an element with content-visibility: auto style when
the rendering state changes and the element either becomes or stops being relevant to the user.
This event is dispatched by posting a task at the time when the state change occurs.
[Exposed =Window ]interface :
ContentVisibilityAutoStateChangedEvent Event {(
constructor DOMString ,
type optional ContentVisibilityAutoStateChangedEventInit = {});
eventInitDict readonly attribute boolean skipped ; };dictionary :
ContentVisibilityAutoStateChangedEventInit EventInit {boolean skipped =false ; };
Description of ContentVisibilityAutoStateChangedEvent attributes:
skipped
, of type boolean, readonly-
Set to true if target changed state to skip its contents, and false otherwise.
Description of ContentVisibilityAutoStateChangedEventInit members:
Note that elements in content-visibility: auto subtrees remain semantically relevant even for elements that skip its contents. This means that it is inappropriate to use this signal to indefinitely skip DOM updates in the subtree that is skipped. Instead, it should be used to deprioritize updates, but ensure that the content remains semantically relevant and reasonably up-to-date. This is particularly important for assistive technologies which consume this content even when the ancestor is set to skip its contents.
4.4. Restrictions and Clarifications
-
From the perspective of an
IntersectionObserver
, the skipped contents of an element are never intersecting the intersection root. This is true even if both the root and the target elements are in the skipped contents. -
From the perspective of a
ResizeObserver
, the skipped contents of an element never change their size. If these elements become non-skipped later, the resize observation will be delivered if the new size differs from the last size used to notify the resize observer. -
If an element starts or stops skipping its contents, this change happens after the requestAnimationFrame callbacks of the frame that renders the effects of the change have run. Specifically, such changes will take effect between steps 13 and 14 of Update the Rendering step of the Processing Model (between “run the animation frame callbacks” and “run the update intersection observations steps”).
Determining the viewport intersection of the element can be done with an internal version of an IntersectionObserver. However, since the observations from this are dispatched at step 14 of Update the Rendering, any changes to the skipped (and thus painted) state will not be visible to the user until the next frame’s processing. For this reason, updating the skipped state, including containment adjustments, is deferred to that frame as well. This ensures that script accessing, for example, the containment value of the element between these two events (internal intersection observation and skipped state update) will retrieve values consistent with current painted state and not cause any forced layouts. -
The initial determination of visibility for content-visibility: auto must happen in the same frame that determined an existence of a new content-visibility: auto element.
When an element first gains content-visibility: auto, it may or may not be positioned on screen. The determination of this state and thus determination of whether this element is skipped must happen in the same frame. If it does not, then there is a possibility of producing blank content in the element’s place since visibility check and skipped state update would be deferred to the next frame. -
For the purposes of scrolling operations, such as
scrollIntoView()
, an element with content-visibility: auto that is skipping its contents has its size and location determined with size containment still active.Note: Once it’s scrolled into view, the element will no longer skip its contents, and so might not have size containment; if this changes the element’s size, it might not align in the viewport exactly as requested.
If an element is not available to user-agent features (for example, if it is skipped due to a content-visibility: hidden ancestor), then scrolling operations must not scroll to it at all, as if it did not have a layout box.
-
If an element with content-visibility: auto that is skipping its contents is focused (or its contents are), it becomes relevant to the user (and thus stops skipping its contents) before it is scrolled into view due to the focusing.
Note: Thus, unlike the previous point, the element will be correctly sized and aligned in the viewport. This is consistent with the order of the steps for the
focus()
method. -
If an
iframe
skips its contents or is part of an element’s skipped contents, the user agent should entirely skip the Update The Rendering step in the iframe’s event loop, if possible.Note: At the moment the
iframe
starts being skipped, it needs to run that step at least once to remove the painted output. -
Skipped contents do not contribute to the result of
innerText
. -
While an element is skipped, CSS transitions and animations on the element do not update:
-
New animations are not created even if newly-applied style would start one.
-
Existing animations do not advance in their timeline.
-
Running animations on the element do not end.
If script queries the style of a skipped element (causing a style change event) such that knowing the state of animations or transitions is required to return correct information, animation and transitions are sampled according to the styles at the time of that style change event:
CSS Animations 2 § 4 Animation Events and CSS Transitions 2 § 5 Transition Events defines what objects are created and what events are fired, with what data, when an animation or transition is updated,.
When an element stops being skipped, animations and transitions are sampled and then resume advancing on their timelines as normal from that point.
Note: Overall, this is similar to the behavior of transitions/animations when a background tab is brought back to the foreground, allowing user agents to skip as much unnecessary animation work as possible without overly disrupting the animations when they become relevant again.
-
-
While an element is skipped, it must not start any transitions, even if a style change event affects its computed styles.
When an element stops being skipped, it must not start any transitions as a result of the style change event associated with it no longer being skipped.
Note: This is similar to an element switching from display:none to a non-none value—
even though the styles are technically changing in that case (from their initial values to their "proper" values from the cascade), no transitions are started. -
If an element has an ancestor with content-visibility: hidden, and it is placed in the top layer, it does not generate any boxes, as if it were display: none.
Note: An element skipped for other reasons, such as having a content-visibility: auto ancestor, will still generate boxes as normal, and might thus become un-skipped.
4.5. Accessibility Implications
If a user agent exposes some form of "accessibility tree", akin to the DOM tree but specialized for accessibility use-cases such as screen-readers (thus providing the positions/etc of elements relevant to accessibility APIs, such as focusable elements), then the skipped contents of content-visibility: hidden elements must similarly be "skipped" (omitted) in the accessibility tree (similar to how display: none elements are omitted in all views of the document).
Skipped contents of content-visibility: auto elements must not expose the fact that a user is interacting with the page via the accessibility tree, rather than via rendering visually to the screen. In particular, if a user agent uses content-visibility: auto to avoid doing layout and painting work on off-screen content for displaying to the screen, it must similarly avoid doing that work on off-screen content for representing in the accessibility tree. If this is not possible (for example, if the user agent’s representation of a focusable element in the accessibility tree requires knowledge of its exact position, and thus requires a full layout to be done on it and surrounding contents), then the user agent must omit the skipped contents from the accessibility tree entirely.
Note: This requirement is intended to protect users utilizing accessibility tooling from being identified and profiled as such via observation of timing channels; if a user agent can skip significant amounts of work when rendering visually, but has to do all of the work when rendering to an accessibility tree, then an author can tell how a user is interacting with the page by observing the timing of layout operations.
4.6. Examples
< style > . sv { content-visibility : auto ; min-height : 50 px ; } </ style > < div class = sv > ... some content goes here ...</ div >
The .sv element’s content-visibility: auto value lets the user-agent manage whether the element is skipped. Specifically when this element is near the viewport, the user-agent will begin painting the element. When the element moves away from the viewport, it will stop being painted. In addition, the user-agent should skip as much of the rendering work as possible when the element is skipped.
< style > . sv { content-visibility : hidden ; } </ style > < div class = sv > ... some content goes here ...</ div >
In this case, the element is skipped regardless of viewport intersection. This means that the only way to have the contents painted is via script updating the value to remove content-visibility or change its value. As before, the user-agent should skip as much of the rendering in the contents as possible.
An additional effect of skipping rendering is that the layout state of the contents can be preserved by the user-agent, so that removing the content-visibility property in the future will cause the contents to be rendered quicker than if they were hidden with display: none or similar.
< style > body { margin : 0 ; } . sv { content-visibility : hidden ; position : relative ; left : 10 px ; top : 20 px ; } # child { position : relative ; left : 1 px ; top : 2 px ; width : 100 px ; height : 200 px ; } </ style > < div id = target class = sv > < div id = child ></ div > ... some other content goes here ...</ div > < script > ... // This will force rendering work, including layout, // if the UA previously avoided it. target. firstElementChild. getBoundingClientRect(); ... </ script >
Similarly to the last example, the element is skipped.
The user-agent should avoid as much rendering work as possible.
However, in this example, at some point script accesses a layout value in the element’s contents.
In this situation, the user-agent cannot avoid rendering work
and has to process any previously skipped rendering work
in order to return a correct value to the caller.
In this example, the result of getBoundingClientRect()
is a rect positioned at (11, 22) with a size 100x200.
Note that repeated calls to the same layout value should not cause any additional rendering work, since the user-agent should retain the last updated rendering state.
Also note that this situation in which rendering work is required is not unique. There may be other situations in which the user-agent cannot avoid rendering work.
5. Privacy Considerations
There are no known privacy impacts of the features in this specification.
6. Security Considerations
There are no known security impacts of the features in this specification.
Like any other CSS specification, it affects the rendering of the document, but does not introduce any special ability to present content in a misleading way that was not previously available through other CSS modules and that isn’t inherent to the act of formatting the document.
Appendix A. Changes
This appendix is informative.
Changes from 2020-12-16 Working Draft
-
Included style containment in the strict and content keywords.
-
Use the overflow clip edge rather than the border edge when deciding if the element is “on screen”, as part of determining if it is relevant to the user
-
Define how animations and transitions act on skipped elements
-
Remove "at risk" marker from style containment
-
Disable propagation from the HTML body element when containment is on
-
Clarify that scrollIntoView() doesn’t scroll to children of a content-visibility:hidden element
-
Defined that elements having an ancestor with content-visibility: hidden don’t generate boxes in the top layer
-
Defined that being in the top-layer makes an element relevant to the user
-
Noted that paint effects with non-local effects can limit certain optimization opportunities.
-
Add ContentVisibilityAutoStateChanged event
Changes from 2020-06-03 Working Draft
-
Changed how the computed values of the contain property are determined
-
Fixed a syntax error in the note about contain: content
-
Change terminology: replace "containing box" with "containment box" (in sync with the same improvements made to Level 1)
-
Editorial improvements and clarifications to size and paint containment (in sync with the same improvements made to Level 1)
-
Be explicit that size containment suppresses natural aspect ratio (in sync with the same improvements made to Level 1)
-
Change the animation type of content-visibility from discrete to not animatable
-
Add constraint on the timing of the initial determination of visibility for content-visibility: auto in § 4.4 Restrictions and Clarifications
Changes from 2019-11-11 Working Draft
-
Define the interaction between paint containment and overflow-clip-margin
-
Add the content-visibility property
Changes from CSS Containment Level 1
-
Restored style containment, which had been dropped from Level 1