Home > Designing, Others > The `hidden` Attribute is Visibly Weak

The `hidden` Attribute is Visibly Weak

October 16th, 2019 Leave a comment Go to comments

There is an HTML attribute that does exactly what you think it should do:

<div>I'm visible</div>
<div hidden>I'm hidden</div>

It even has great browser support. Is it useful? Uhm. Maybe. Not really.

Adam Laki likes the semantics of it:

If we use the hidden attribute, we make our semantic a little better. Anybody will understand what does a “hidden” attribute means on an element.

Monica Dinculescu calls it a lie:

the hidden rule is a User Agent style, which means it’s less specific than a moderate sneeze. This means that your favourite display style will override it:

<style>
  div { display: block; }
</style>
<div hidden>
  lol guess who's not hidden anymore
  hint: it's this thing
</div>

So two related problems…

  1. It’s extremely weak. Literally any change to the display property other than the none value on the element with any strength selector will override it. Much like any other display property, like width or whatever, except the it feels somehow worse to have a hidden attribute actively on an element and have it not actually be hidden.
  2. The display property is sadly overloaded with responsibility. It would be way cool if hidden was a CSS property that could be in charge of the visibility/access of elements rather than the same property that controls the type of block it is. But alas, backward compatibility 4-lyfe of the web stops that (which is a good thing for the health of the web overall).

If you really love the semantics of the attribute, Monica suggests:

[hidden] { display: none !important; }

Seems like a nice addition to any “reset” or base stylesheet.

Otherwise, the classic technique of hiding things with a class is absolutely fine. I typically have a utility class:

.hide, .hidden {
  display: none;
}

But remember there are always a million ways to do things. I find myself regularly doing one-off hide/show mechanisms. For example, a menu that you need to toggle the visibility of with flair, but remain accessible at all times…

.menu {
   opacity: 0;
   visibility: hidden;
   transition: 0.2s;
   transform: translateX(20px);
   &[data-open] {
     opacity: 1;
     visibility: visible;
     transform: translateX(0);
   }
}

The post The `hidden` Attribute is Visibly Weak appeared first on CSS-Tricks.

Categories: Designing, Others Tags:
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.