2017-10-28 138 views
1

我想用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> 

任何想法,我該怎麼辦呢?

回答

0

如果指定的模態體的高度,你可以允許模態的身體滾動與他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; 
    } 
} 
+0

的問題是,我不知道身體的高度提前。 .body的內容可能很高或很短,我只希望它在不適合屏幕時滾動。 – aherriot

+1

在這種情況下,您可以使用max-height而不是height? – TidyDev

+0

嗯,不,因爲沒有最大高度。最大高度是它必須適合在屏幕上。 – aherriot

相關問題