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
    5 More HTML5 APIs You Didn’t Know Existed

    The HTML5 revolution has provided us some awesome JavaScript and HTML APIs.  Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers.  Regardless of API strength or purpose, anything to help us better do our job is a...

  • By
    CSS vs. JS Animation: Which is Faster?

    How is it possible that JavaScript-based animation has secretly always been as fast — or faster — than CSS transitions? And, how is it possible that Adobe and Google consistently release media-rich mobile sites that rival the performance of native apps? This article serves as a point-by-point...

Incredible Demos

  • By
    Google Font API

    Google recently debuted a new web service called the Font API.  Google's Font API provides developers a means by which they may quickly and painlessly add custom fonts to their website.  Let's take a quick look at the ways by which the Google Font...

  • By
    MooTools: Set Style Per Media

    I'd bet one of the most used MooTools methods is the setStyle() method, which allows you to set CSS style declarations for an element. One of the limitations of MooTools' setStyle() method is that it sets the specific style for all medias.

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!