Quick Tip: The Awesome Details Element

Quick Tip: The Awesome Details Element

Tutorial Details
  • Difficulty - Beginner

One of my favorite new HTML5 tags, which has only recently been integrated into Chrome (as of version 12), is the details element. I’ll show you to use it in today’s quick tip.


What Does the details Tag Do?

It essentially allows us to show and hide content with the click of a button. You’re surely familiar with this type of effect, but, up until now, it had always been achieved with JavaScript. Imagine a heading with an arrow next to it, and when you click on it, additional information below becomes visible. Clicking the arrow again hides the content. This sort of functionality is very common in FAQ pages.

Here’s a two minute example of this sort of effect. (Type Control + Enter to process the JavaScript.)

The details element allows us to omit the JavaScript entirely. Or, better put, it eventually will. Browser support is still a bit sparse.

image

An Example

So let’s dive in and learn how to use this new tag. We begin by creating a new details element.

<details>

</details>

Next, we need to give it a title, or summary of the content within.

<details>
	<summary> Who Goes to College? </summary>
</details>

By default, in browsers that understand the details element, everything within it — other than the summary tag — will be hidden. Let’s add a paragraph after the summary.

<details>
	<summary> Who Goes to College? </summary>
  <p> Your mom. </p>
</details>
Default Display

Go ahead and try the demo out in Chrome 12 or higher (as of November 17th, 2011).

Okay, let’s do something a bit more practical. I want to display various Nettuts+ articles using the details element. We first create the markup for a single article.

<details>
   <summary>Dig Into Dojo</summary>
   <img src="https://d2o0t5hpnwv4c1.cloudfront.net/1086_dojo/dojo.jpg" alt="Dojo" />
   <div>
      <h3> Dig into Dojo: DOM Basics </h3>
      <p>Maybe you saw that tweet: “jQuery is a gateway drug. It leads to full-on JavaScript usage.” Part of that addiction, I contend, is learning other JavaScript frameworks. And that’s what this four-part series on the incredible Dojo Toolkit is all about: taking you to the next level of your JavaScript addiction.  			
     </p>
   </div>
</details>
image

Next, we’ll give it just a touch of styling.

body { font-family: sans-serif; }
	
details {
  overflow: hidden;
  background: #e3e3e3;
  margin-bottom: 10px;
  display: block;
}

details summary {
  cursor: pointer;
  padding: 10px;
}

details div {
  float: left;
  width: 65%;
}

details div h3 { margin-top: 0; }

details img {
 float: left;
 width: 200px;
  padding: 0 30px 10px 10px;
}
image

Please note that I’m showing you the open state for convenience, but, when the page loads, you’ll only see the summary text.

If you’d prefer to be in this state by default, add the open attribute to the details element: <details open>

Styling the Arrow

It’s not quite as straight-forward to style the arrow itself as we might hope. Nonetheless, it is possible; the key is to use the -webkit-details-marker pseudo class.

details summary::-webkit-details-marker {
  color: green; 
  font-size: 20px;
}
Styling the arrow

Should you need to use a custom icon, possibly the easiest solution is to hide the arrow (using the pseudo class above), and then either apply a background image to the summary element, or use the :after or :before pseudo elements.

View the final project.


Conclusion

It’s certainly a simple effect, but it sure is nice to have such a common feature built-in. Until we can reliably use the details element across all browsers, you can use this polyfill to provide fallback support. One final note: at the time of this writing, there doesn’t seem to be a way to toggle the contents with a keyboard. This could potentially present some accessibility issues.

Tags: html5tips
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Jonathan Hernandez

    Awesome, I liked it!

  • Bryce Pelletier

    Yeah this will be a nice tag (someday). As with most HTML5 tags though nothing can be done with them in the corporate world since many corps are stuck in the figurative stone age of browsers. Disney as a whole just updated to IE7. Finally trickled down to the department I work for back in July.

    Yeah at least we are done with IE6 though. Thanks for the amazing posts. Cheers

    • Brad

      Dont feel bad, Books a Million store computers run on Win 95

      • http://www.web-cooperative.com Web Cooperative

        Ouch.

        My first job, many moons ago in 2001, was in DIY store. A nationwide chain. Their systems were running off Win 3.1. I was bemused when I saw how it worked. When I moved on in 2003 they were updating I think…probably to NT4.

        Shows how companies spend fortunes on an IT system and then keep it, in computing timescales, “forever”.

  • http://ilm4all.blogspot.com M. Ahmad Zafar

    Any idea how we can style the arrow that is displayed?

  • http://www.gabrielmateus.com Gabriel Mateus

    This way it’s much more pratical to get this effect without javascript :D
    But, because of the browser support it’s only a desire.

    ps: sorry, my english sucks. Eu sei.

  • http://nightfirecat.right-0n.com/ Jordan

    Nice article. Not the first I’ve seen, but it just gets me excited for eventual growing browser support for it.

    I’m curious – after taking a quick look through the current CSS3 spec, there doesn’t seem to be much definition on styling of <details> elements yet - of the element as a whole, or targeting it when it is in collapsed or expanded states. Do you know if there are any such selectors yet, or if they're still working their way into the draft?

  • http://brocknunn.com Brock Nunn

    My mind has been blown! That is so awesome! I just need to figure out how to work in some css transitions to make it more silky, but what a nice thing to have built right in.

    However, how risky will it be to use with such low browser support? Does polyfill work well?

  • http://helikopta.com Bill

    Why do they give the new html5 tags such bad names? Would have been better named Toggle.

    • Mecha

      That is too close to google ;) Is “google” a tag yet?

    • Sebastiaan Franken

      Because it is semantically valid this way. All the new HTML5 tags are semantically valid (header, footer, article, section, aside …)

  • http://www.stefan-reimers.de/ Stefan

    I stick with Bryce: As long as Chrome is the only one supporting it, the details tag will remain unused. I have posted about a workaround for other browsers using jquery to emulate this functionality on http://www.phpundmysql.de/2011/10/22/das-html5-summary-tag-mit-allen-browsern-nutzen/.

    The post is in German, but the code example on the end of the page should be self explanatory.

  • http://www.jsvrocks.com/ Sandeep

    From which site is the image below text “The details element allows…Browser support is still a bit sparse.” from?

    I just remembered the UI and forgot the url. That’s a good site.

  • Kuba

    That’s awesome! Unfortunately it’s not working on Opera 11.50.

  • http://blog.piotrnalepa.pl sunpietro

    It’s very interesting indeed. Unfortunatelly, it only works in Google Chrome natively.
    It can be useful in the future, not now.

  • http://www.kecioyun.com/ Oyun

    Very cool tutorial. I did not know detail tag can do so much.

  • http://www.web4you.co.in Deven

    The concept of HTML5 looks really interesting but i am still afraid to use because of browsers compatibility issues.

    • Sebastiaan Franken

      The browsersupport for HTML5 is actually quite good. You can use the normal markup tags in your site with no penalty (just add the html5shiv javascript from googlecode) for IE8 and lower. It should be no problem.

  • http://www.paint-zoom-reviews.com Ori

    Great stuff, But it can take at least 2 years to be supported in all browsers.
    What is it shows in the browsers that don’t support this feature?

  • http://rommelcastro.me Rommel Castro A.

    is just awesome!

  • http://www.github.com/dotink Matthew J. Sahagian

    It’s official. I’m NEVER switching to HTML5. This is the final straw…

    “if you want this to be in this state, add the open attribute”

    – So now my HTML elements have attributes which define their behavior/presentation? Can’t wait till the “marque tag” is added with it’s amazing “direction” attribute.

    You can “make an argument” that browser have always defined DEFAULT behaviors and presentations… and always should. And while I agree with that… they do so according to elements/attributes that have additional semantic meaning. I see no such value for the open attribute.

    • Sebastiaan Franken

      But what if your site demands that the first item is shown opened? How would you prepose to do that? With something like this:

      details:first-child{
      state: open;
      }

      Or, even worse, with javascript (which can be disabled in browsers..)?

      You can take semantics too far. The web still has to be usable

      • http://www.github.com/dotink Matthew J. Sahagian

        In my opinion the default state SHOULD be open. If I want the default state to be “closed” — i.e., not visible, I already have a means to do this:

        details {
        display: none;
        }

        If you look at my post further down I have proposed a method in which one could “attach” a handler to the details the same way that we attach a label to an input element, using the “for” attribute. Defining my handler as an element makes a lot more sense to me. The fact of the matter is, the summary element could very well be used without details, and the details could just be a link to another page.

        My proposal is 100% semantic, does not IMPLY any behavior what so ever, makes for easy styling, easy behavior, etc, and puts the default behavior on an element we are already familiar with having default behavior, an anchor.

    • http://nightfirecat.right-0n.com/ Jordan

      So then, I suppose something like <input type=”checkbox” checked=”checked” />, or its HTML5 alternative <input type=”checkbox checked /> is equally atrocious? This isn’t a novel concept, nor do I think it’s inconsistent with the rest of the HTML doctype.

      • http://www.github.com/dotink Matthew J. Sahagian

        There is a huge difference between a “checked” state on an inline element and an “open” state, which really reflects presentational information ONLY.

        Checked implies a state of the data, the same way options are selected, and even text inputs might have default values. These are not purely presentational things. Open, however, is. You might be able to argue that it represents the document state for the user, but the document state for the user is much more behavioral and presentational, the document state in it’s natural form is ALL about the data.

        It’s really that simple, if you can’t see that, then I don’t know what else to say.

        As I have said in other comments here and elsewhere. We grasp that certain things in browser have default behavior and presentations, just because that is and probably should be the case on a limited number of things, does not mean we should open them all up.

        There is no doubt in my mind that we will need Javascript Resets much the way we need CSS ones very soon.

  • Habanero

    It makes no sense why W3C make stuff like this. They look retrospectively at what people have been doing with the tools that exist and then announce something as random as this. Header tags? Footer tags? What are they smoking! Someone else needs to take charge of the future of the web because these guys are absolute jokers.

    This can be done in JS, and it should be done in JS. It has always been done in JS and this ‘feature’ wasn’t dreamed up by a committee it was created by true creative individuals working with the bizarre tools that we’ve got.

    This isn’t design, this isn’t best practices, this is madness!

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      “Header tags? Footer tags? What are they smoking!”

      What’s your problem with those tags?

      • Habanero

        My problem with them is that we’ve been making headers and footers for years and years with DIV tags or whatever and styling them as such, all the while we’ve been fighting problems of cross compatibility that might have been solved if the W3C had taken a more pragmatic approach to their specs (for example, by releasing their own open source implementation of their standards, we have that now and we’ve seen Apple for example adopt one of those standards).

        Still we have the problem of W3C’s recommendations taking years to get implemented and usable by the general web population. The technology that brought the web forward was things like JQuery that wrapped up the huge differences of things like the Events API (that had been in the spec for years, but hardly anyone used them).

        So what I mean is when we have these real problems: how do we get these good ideas implemented sooner rather than later, and in such a way that programmers can use them properly cross browser, and who should be coming up with this in the first place? A committee? Then the W3C say “we have been deliberating and this is what we’ve come up with, a tag, a tag!”. It’s like being chronically malnourished and your senile grandfather handing you a small lollypop.

        So it’s not a criticism of your post or anything like that, but a reaction to a lollypop when oh man I am STARVING!

      • http://www.github.com/dotink Matthew J. Sahagian

        As I have mentioned in other threads regarding HTML5, there are two types of semantic elements.

        Firstly there are those which have meaning in the document and relative to a site or collection of documents as a whole. These are fairly limited in number and are, with HTML5, for the most part “complete.” I LOVE this aspect of HTML5.

        The second type is those which have semantic meaning on a human data aggregation level. I see HTML5 beginning to enter into this realm, and it is starting to concern me. There are simply too many types when it comes to this information. Article, Summary, and Detail are beginning to infringe on that. Then on top of this we have Microdata, which in my opinion is just a mess, and sometimes defines no additional semantic value, such as in the case of lists and items.

        Now, in addition to this, it’s starting to infringe on the areas of behavior and presentation, which is precisely what we tried to get away from for the past 10 years or so since CSS and JS started to come of age.

        The fact that browsers have default behavior and presentation for elements is a moot point, it is the reason we have CSS resets and why we consider it good practice to remove styles and normalize them to begin with. Thankfully behavior has been fairly limited (clicking buttons submits, clickling links follows them). If we continue down this road, however, we are pretty soon going to need not only greatly expanded CSS resets, but also JS resets.

        What is even doubly bad abou this, is how the hell do we target this little arrow? It is not an element itself, but something (as far as I can tell, not even represented in the DOM). How do I prevent the default action if I want to? How do I style it?

        At the very least they should make use of existing attributes and allow us to, for example to define an anchor with a for attribute matching the ID of the details.

        <article>
        <summary>
        <p>Lorem Ipsum…<a for=”article-01_details”>Read More</a></p>
        </summary>
        <details id=”article-01_details”>

        </details>

      • http://net.tutsplus.com Jeffrey Way
        Author

        I get what you’re saying, Ryan, but I’m not sure how desiring bigger solutions and fixes translates to something like the `nav` element being “just a tag” and unnecessary. Yes, it’s just a tag, but it’s more than just a replacement for div id=”nav”. There’s considerable accessibility benefits to these new elements.

        But on the speed issue, yeah, I agree with you.

      • http://net.tutsplus.com Jeffrey Way
        Author

        Matthew – you’d target the arrow with “summary::-webkit-details-marker {}”.

        But I sorta agree on this. It’s really difficult to target some of these new elements, where the browser seems to hide it. The same is true for the new input types, like number tickers. There are ways to target it, but I worry that it’s too complicated.

      • http://net.tutsplus.com Jeffrey Way
        Author

        Also Ryan, I can appreciate the “this should be done with JavaScript” line of thinking. There’s some truth in that. But, on a more ‘getting the job done’ level, if I can accomplish a particular effect directly in the browser, why would I prefer to risk using JavaScript instead – and all that comes with that (disabled JS, etc.)?

      • Habanero

        The reason why I’d say “go for it with JS” is because using JS to build generic interactive elements such as this is a more generic solution. I rate flexibility higher than the conciseness of a single tag, and I’m willing to write a tiny bit more code whether that be JS or HTML to afford more flexibility and customisability.

        At a tactical level the details tag seems to make some sense, but as someone who tries to understand the whole from the parts things like this in HTML scream non sequitur. How does this fit into the web as a whole? I can’t see how it’s supposed to fit. It feels arbitrary.

        As for my mad ravings about specialist tags, that’s a whole other story and an essay unto itself. I’ll try to gather my thoughts on the issue and try to present it in such a way that I don’t sound like a raving lunatic.

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        Write it up, and give me a dang article for Nettuts+. :)

  • http://www.webflysoftware.com adumpaul

    Great useful post.Thank you.

  • Kristof

    I hate to be negative after all those “awesome!”-comments, but what is the purpose of this element?

    Isn’t it basically a definition list with one item that has a default state of hiding the dd? As much as I like the direction HTML5 is going, I think this is just plain useless, regarding semantics.

    Cluttering up the standard with yet-another-element that defies the purpose of separating semantics and presentation by hiding elements by default… As useful as the input types may be, I truly hope it won’t come to a point where popular UI patterns are implemented into the HTML spec!

  • Brad

    I have little doubt that in time CSS and HTML will be one language. And that’s not a problem for me

  • Darren

    Jeff, It’s nice, but is there a way to make it transition to the “open” state in a nice way by using CSS3?
    Obviously, JavaScript has ‘other’ niceties that we can do, like sliding or fading in. It would be criminal if we could use this tag and had to then use JS to make it transition in a nice way.

    Cheers.

  • Mahesh

    Very nice article. There is a addon to check what browsers support what html5 features. Its called Modernizer.js. Start HTML5 & Modernizer here
    http://www.msguy.com/2011/10/html-5-some-more-details-and-intro-to.html

  • http://www.celladda.com Muktar

    that was excellent. i really like it. but the demo link not working for me :(

  • w1sh

    Love Quick Tips. Thanks JW

  • http://skype mudassar butt

    hi jeff, how u create all new programing

  • http://www.esarkarinaukri.org Sanjeev

    Really great. thanks for sharing.

  • Fuad

    details div {
    float: left;
    width:65%;
    }

    I am a little confused on the above css code. Which i didn’t get it why i use width here. theoretically float:left should have been worked but when i was remove the width the div went down below the dojo image but the funny thing is if i didn’t use the float, it worked just fine. what went wrong?

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Because, without the width, the div will still, by default, take up 100% of the available room.

  • http://www.facebook.com/hr.afshari hamid

    Hi
    I was a good
    I translated the written permission of the author

  • http://twitter.com/anastasialanz Anastasia Lanz

    The link to the final project doesn’t work. Do you have another working site?