Auto-growing modal Dialog in CSS that should not grow out of screen

Viewed 230

I am currently working on a web app targeting tablets. I would like to show a modal dialog (titlebar + body) that grows (in height) no bigger than it's content requires, but if the content demands a height that would be bigger than the viewport, the dialog should instead have a scroll bar on the body element and a maximum height of the viewport's/parents height.

Can I somehow achieve this with CSS/JS?

2 Answers

You could probably just use max-height: 100vh; and overflow-y: auto;.

Feel free to reduce the value of max-height or use calc(100vh - 30px) as a value if you need to remove some margin from the height of the modal.

You were so close Here take a look i added overflow-y: hidden; to .dialog and it works

.screen {
    width: 800px;
    height: 200px;

    font-family: sans-serif;
    display: grid;
    place-items: center;
    background-color: gray;
  }

  div.titlebar {
    background-color: green;
    height: 32px;
    display: grid;
    place-items: center;
  }

  div.body {
    overflow-y: scroll;
    background-color: purple;

    /* setting height to 100% (of the parent) */
    /* minus the 32px of the header */
    height: calc(100% - 32px);
  }

  div.dialog {
    width: 400px;
    height: auto; /* auto size ... */
    max-height: 100%; /* ... but dont grow bigger than screen */
    display: flex;
    flex-direction: column;
    background-color: yellow;
    overflow-y: hidden;
  }
<div class="screen">
      <div class="dialog">
        <div class="titlebar">Title</div>
        <div class="body">
          Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error
          praesentium aut laboriosam modi eius ex cum, ullam placeat, beatae,
          nobis est quasi voluptate alias necessitatibus excepturi? Voluptas,
          ut! Maxime consequuntur, quod? Ipsa ullam eveniet, dolore voluptas
          eius obcaecati vero sint aut at sapiente! Vel iure distinctio pariatur
          maxime, illo ab voluptate veritatis, porro delectus, earum molestiae
          at ipsam ducimus dicta. Laboriosam perspiciatis molestias voluptatibus
          modi dolorem ea asperiores assumenda alias minus, saepe facilis nam
          consequuntur nulla ipsum delectus totam itaque consequatur molestiae.
          Quibusdam nam, vero fugit mollitia minima dolor, eveniet obcaecati
          sint iste inventore explicabo eligendi ratione harum, tempore quasi.
        </div>
      </div>
    </div>

Related