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
    I’m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

  • By
    5 Ways that CSS and JavaScript Interact That You May Not Know About

    CSS and JavaScript:  the lines seemingly get blurred by each browser release.  They have always done a very different job but in the end they are both front-end technologies so they need do need to work closely.  We have our .js files and our .css, but...

Incredible Demos

  • By
    Basic AJAX Requests Using MooTools 1.2

    AJAX has become a huge part of the modern web and that wont change in the foreseeable future. MooTools has made AJAX so simple that a rookie developer can get their dynamic pages working in no time. Step 1: The XHTML Here we define two links...

  • By
    Optimize Your Links For Print Using CSS — Show The URL

    When moving around from page to page in your trusty browser, you get the benefit of hovering over links and viewing the link's target URL in the status bar. When it comes to page printouts, however, this obviously isn't an option. Most website printouts...

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!