HTML Hidden Attribute

HTMLPosted on

The HTML hidden attribute is a small feature that makes it possible to hide any element easily.

It was introduced with HTML5 and works similarly as the CSS display: none; declaration. If you set the hidden attribute to an element, it will disappear from the view.

This behavior is mostly needed if we create a programattic routine. If we have a modal which content is in our DOM, but we only want to show it when the user opens it, we can use the hidden attribute. We don’t have to give a value to this property; if it exists on an element, it will be true.

<div class="modal-content" hidden>
    Hello, I'm a modal!

Use the Hidden Attribute Because of the Semantic

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.

Although it is a neat small feature, we can have compatibility problems. If we want to be more inclusive, the best way is always to use a technique that is supported the best. A pure class with display: none; can achieve better results, but it depends on the project too. If you want to learn more about the CSS hiding techniques, visit our other article.

The hidden attribute will hide the content from the screen readers too.

For more support we can also make a small “polyfill” in CSS like so:

*[hidden] { display: none; }

The browser support is quite good as you can see on Can I use.

Be Cautious With the Low Specificity

One thing is easy, to override the hidden attribute behavior through CSS. If you want to use this attribute to hide something, you must keep in mind that it is weak. Generally, it is an attribute selector on the user-agent. You can override it with everything from a simple class selector.

In the case of a complex project, it is good to use the following line in your reset:

[hidden] { display: none !important; }

The previous example is in use in PureCSS and Bootstrap 4’s reboot.

Need a web developer? Maybe we can help, get in touch!

Similar Posts

More content in HTML category