CSS content-visibility

By  on  

The CSS language is full of small gaps which are frustrating to navigate. Between CSS properties to hide a container and its contents, there is still room for improvement. visibility: hidden keeps height and width integrity while display: none on a container hides everything. You can use .container > * to hide all contents of a container, but what if there was a better way?

There is a better way to hide the contents of an element while respecting the container's border and dimensions. That better way is using the content-visibility property:

.my-container.contents-loading {
  content-visibility: hidden;
}

A demo of such functionality:

See the Pen Untitled by David Walsh (@darkwing) on CodePen.

Avoiding a .container > * selector by using content-visibility: hidden is so much nicer from a maintenance perspective!

Recent Features

  • By
    Conquering Impostor Syndrome

    Two years ago I documented my struggles with Imposter Syndrome and the response was immense.  I received messages of support and commiseration from new web developers, veteran engineers, and even persons of all experience levels in other professions.  I've even caught myself reading the post...

  • By
    Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() - this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

Incredible Demos

Discussion

  1. Chris Zuber

    I’ve found that it can cause accessibility issues and false problems in Lighthouse reports. But that’s content-visibility: auto.

    For example, I have large white text on a black background in a footer, but I think Chrome doesn’t properly test/paint it/something because it says all text has insufficient contrast ratio (it has a ratio of like 12). Screen readers also seem to be problematic, though I can’t say exactly what’s going on there.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!