htmlcssflexboxhtml-tag-details

Details element, fit to content whilst inside a flex box, even when collapsed


When placing an <details> element inside a <div> with display: flex the width of the <details> element will equal the <summary> element when collapsed and will grow when uncollapsed to fit its content.

Example:

.flex {
  display: flex;
}

details {
  background-color: red;
}
<div class="flex">
  <details>
    <summary> short </summary>
    <p> very long and detailed description </p>
  </details>
</div>

What I want is that the width of the <details> element is consistent regardless if it is collapsed or not. Ideally such that it fits its content.

In short how do I prevent it from shrinking when collapsed.


Solution

  • Specify a flex-basis on details.

    .flex {
      display: flex;
    }
    
    details {
      background-color: red;
      flex-basis: 50%;
    }
    <div class="flex">
      <details>
        <summary> short </summary>
        <p> very long and detailed description </p>
      </details>
    </div>