Alpine.js: responsive x-cloak

When using Alpine.js the x-cloak attribute is removed from DOM elements when Alpine is initialised. As noted in the docs, this makes it useful for hiding elements until Alpine is initialised:

x-cloak attributes are removed from elements when Alpine initializes. This is useful for hiding pre-initialized DOM. It's typical to add the following global style for this to work:

2 [x-cloak] { display: none; }

You may want to hide pre-initialised DOM on some screen sizes, but not others. A good example for this is the links in a site's navigation bar, which are typically hidden by default on smaller screen sizes, but are always visible on wider screens.

So instead of hiding all elements with the x-cloak attribute, we can hide only the ones whose x-cloak attribute has no value:

1[x-cloak=""] { display: none; }

This allows us to target elements whose x-cloak attribute has a value:

1[x-cloak="some-value"] { }

So now we can write CSS rules targeting elements whose x-cloak value is mobile, tablet, desktop:

1/* always hidden */
2[x-cloak=""] { display: none; }
4/* hidden on mobile/smaller screens */
5@media screen and (max-width: 768px) {
6 [x-cloak="mobile"] { display: none; }