Auto-growing CSS 中的模态对话框不应超出屏幕

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

我目前正在开发一个针对平板电脑的网络应用程序。我想显示一个模态对话框(标题栏+ body)(高度)增长不超过其内容所需的高度,但如果内容要求的高度大于视口,则对话框应该改为body 元素上的滚动条和视口的最大高度's/parents height.

我能用 CSS/JS 以某种方式实现吗?

您可能只使用 max-height: 100vh;overflow-y: auto;

如果您需要从模式的高度中删除一些边距,请随意减小 max-height 的值或使用 calc(100vh - 30px) 作为值。

你们太亲密了 来看看 我将 overflow-y: hidden; 添加到 .dialog 并且它有效

.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>