Last Updated: September 09, 2019
·
1.966K
· idered

Use 'hidden' attribute instead of additonal classes

HTML5 has an useful attribute - hidden.

<p hidden>I'm a ninja</p>

This will add a display: none; to that paragraph.

For older browsers you can add

[hidden] { display: none; }

to support this attribute.

5 Responses
Add your response

The question is why?

Remember that hidden attribute is not the same thing as css presentation properties. It's just a convenient way of marking elements that are permanently removed from display list.

Please take a look at the docs here.

Also, remember that attribute selectors [attr] are not the best choice when it comes to performance.

over 1 year ago ·

@paprikkastudio And why not? Guys from W3C has created this for devs then why not to use it? Of course this attribute isn't

suitable in many cases but stil, I can find it useful. For example I use it to preload images used in CSS.

<!-- Hidden div to fetch images before CSS needs them -->
<div hidden>
   <img src="img/loader.gif" alt="">
   <img src="img/sprite.png" alt="">
</div>

It's all up to you how you use it :)

over 1 year ago ·

@idered That's a nice example, indeed.
I just think that the title is kinda misleading because @attributes and css properties are not created equal. And in many cases using aria-hidden would make more sense.

I think the first name of this attribute, which was irrelevant was a much better choice, since a lot of people tend to abuse it as a display:none alternative.

over 1 year ago ·

Any idea how this is treated by screen readers?

over 1 year ago ·

@idered Thanks for sharing the tip. As a side comment, I thought it would be worthwhile to note the example of image tags that display non-content visual aids (loaders and such) are counteractive to the distinction drawn between CSS (the visual style of the document) and HTML (the data structure of the document).

The <img> tag has the meaning, "This picture is consumable content that is relevant to the page." e.g. a photograph in a news article is a relevant and impactful piece of data that is related to the rest of the article. In this case the loader is not a relevant or impactful part of the actual content on the page, it is a user interface helper for those who aren't visually impaired.

That said, if semantics are a priority for any future reader, It might be slightly more semantic to have loaders be faceless <div class='loader'> tags with background images.

Outside of that, thanks again for sharing the tip -- I believe you are using the hidden attribute correctly in your use case.

over 1 year ago ·