CSS:当没有足够的空间时,模态窗口滚动主体但不滚动标题

时间:2017-10-28 20:59:10

标签: html css modal-dialog flexbox css-position

我正在尝试使用CSS制作模态窗口。我希望它足够大以适应内容,但是,当屏幕上没有足够的空间时,我希望滚动条出现在模态窗口的主体中,将其标题和按钮行保留在视图中倍。我如何实现这一目标?

当没有足够的空间时我可以正确显示滚动,但是当屏幕尺寸很大时,模态太大了, 要么 我可以正确调整模态大小,但滚动条不会显示。

这是我尝试的jsfiddle。我究竟做错了什么? https://jsfiddle.net/7Lmj0eoj/1/

此外,下面粘贴了相同的源代码:

CSS:

* {
  font-family: sans-serif;
}

.modalBackground {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0,0,0,0.3);
}

.modalWindow {
  background-color: white;
  box-shadow: 0 0 5px 2px #999;
  top: 50%;
  bottom: auto;
  left: 50%;
  right: auto;
  transform: translate(-50%, -50%);
  position: absolute;
  max-width: 350px;

  /*
  if you enable these two lines, the scroll bar appears in the right place,
  but it doesn't get sized correctly when there is enough space to fit the whole thing.
  max-height: calc(100vh - 20px);
  height: 100%
  */

  overflow-y: hidden;
  display: flex;
  flex-direction: column;
}    

.modalWindow .title {
  font-size: 20px;
  margin: 10px 20px;
}

.modalWindow .body {
  padding: 10px 20px;
  border-top: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
  flex-shrink: 1;
  overflow-y: auto;

}

.modalWindow .actions {
  display: flex;
  justify-content: flex-end;
  margin: 10px 20px;
}

HTML:

<div class="modalBackground">
  <div class="modalWindow">
    <div class="title">Modal Title</div>
    <div class="body">
      <p>
        This is the body of the modal window and the only part that should scroll when there is not enough space to fit on the screen. The title and the button section should be outside of the scrollable area.
      </p>
      <p>
      When there is room to fit the whole content of the dialog, it should not be larger than it has to be. In other words, the modal height should be just big enough to fit the content and when there is no room, a scrollbar should appear on the .body div tag.
      </p>
      <p>How can I make this work? Thank you.</p>
    </div>
    <div class="actions">
      <button type="button">Submit</button>
    </div>
  </div>
</div>

我有什么想法可以做到这一点吗?

1 个答案:

答案 0 :(得分:0)

如果指定模态体的高度,则可以允许模态体用其溢出属性滚动:

.modalWindow .body{
  height: 200px;
  overflow-y: scroll;
}

这是CSS滚动https://www.w3schools.com/cssref/pr_pos_overflow.asp

的绝佳资源

修改

根据您的评论,如果屏幕高度低于预定值,则可能需要使用媒体查询来仅引入滚动。

例如:

@media screen and (max-height: 700px) {
    .modalWindow .body{
      height: 200px;
      overflow-y: scroll;
    }
}