Skip to main content

How to style a <details> element differently depending on whether it’s open or closed

If you want to style a <details> element which is open, use the details[open] selector (MDN link):

details[open] {
  background: green;
}

If you want to style a <details> element which is closed, there are two options:

  1. Apply a style with the details selector, and then undo it for the open state with the details[open] selector.

  2. Or if you want to make it clearer that this only applies to the closed element, you combine the :not() pseudo-class and open:

    details:not([open]) {
      background: red;
    }
    

    I got this by guessing, but it works in Safari. This combination of :not and square brackets syntax is new to me, but it seems to be thing!