CSS:模态窗口滚动身体,但没有足够的空间时标题
问题描述:
我想用CSS来做一个模态窗口。我希望它足够大以适应内容,但是,当屏幕上没有足够的空间时,我想要一个滚动条出现在模式窗口的主体中,并将其标题和按钮行保留在视图中倍。我如何实现这一目标?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>
任何想法,我该怎么办呢?
答
如果指定的模态体的高度,你可以允许模态的身体滚动与他overflow属性:
.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;
}
}
的问题是,我不知道身体的高度提前。 .body的内容可能很高或很短,我只希望它在不适合屏幕时滚动。 – aherriot
在这种情况下,您可以使用max-height而不是height? – TidyDev
嗯,不,因为没有最大高度。最大高度是它必须适合在屏幕上。 – aherriot