高度大于页面高度和页面大于覆盖的CSS叠加

问题描述 投票:0回答:3

我尝试创建一个在页面上弹出的菜单。菜单的高度是可变的,可以大于视口和/或页面内容。这是简化的代码:

* {
  margin: 0;
}

#overlay {
  min-height: 100%;
  width: 100%;
  position: fixed;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: start;
  justify-content: center;

}

#popup {
  margin: 50px;
  height: 50vh;
  width: 300px;
  border: 1px solid red;
  background-color: blue;
}
<div id="overlay">
  <div id="popup">
  </div>
</div>

<div id="content">
  Page content
</div>

当页面内容大于视口高度时,即使覆盖在屏幕上,用户也可以滚动页面:

https://jsfiddle.net/Imabot/ydmwLo2j/1/

另一方面,当菜单大于视口高度时,用户无法滚动查看菜单底部:

https://jsfiddle.net/Imabot/ydmwLo2j/2/

我已经用

overflow: scroll;
尝试了很多东西。但没有任何效果。

有解决这两个问题的方法吗?

我已经读过这个问题,但没有帮助:How to make the height REALLY 100%

html css overlay
3个回答
3
投票

只需添加到叠加层:

height: 100%;
overflow: auto;

由于覆盖覆盖了整个页面,滚动条将仅应用于覆盖:https://jsfiddle.net/65na8hy3/

为了防止滚动主要内容,添加:

正文{ 溢出:隐藏; }

一石二鸟,如你所料


1
投票

我给

min-height:100vh
position:relative
值给
#overlay
id。在html文件中,我将所有代码放入
#content
id。我为
#content
添加了背景色并删除了
#overlay
的背景色。将
#content
的高度更改为 300vh.

你可以用codepen控制它:https://codepen.io/yusufdogandev/pen/ZEqWvVe

* {
  margin:0;
}
#overlay {
    min-height: 100vh;
    width: 100%;
    position: relative;
    display: flex;
    align-items: start;
    justify-content: center;
    text-align:left;
    
}

#popup {
  margin: 50px;
  height:200vh;
  width: 300px;
  border: 1px solid red;
  background-color: blue;
  
}

#content {
  height: 300vh;
  background: #4c4c4cb4;
}
<div id="content">
Page content
<div id="overlay">

  <div id="popup">
  </div>
</div>

</div>


0
投票

当模式打开时,在页面的

overflow: hidden
元素上设置
<body>
。当页面高于视口时,这将防止滚动。向模态容器添加最大高度,使其内容在高于视口时可滚动。

const popupContent = document.querySelector('.js-popup-content');
const content = document.getElementById('content');

document.querySelector('.js-demo-0').addEventListener('click', () => {
  popupContent.style.height = '50vh';
  content.style.height = '200vh';
});

document.querySelector('.js-demo-1').addEventListener('click', () => {
  popupContent.style.height = '200vh';
  content.style.height = '50vh';
});
* {
  margin:0;
}

body {
  overflow: hidden;
}

#overlay {
  min-height: 100%;
    width: 100%;
    position: fixed;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: start;
    justify-content: center;
    
}

#popup {
  margin: 50px;
  max-height: calc(100vh - 100px);
  width: 300px;
  border: 1px solid red;
  background-color: blue;
  overflow-y: auto;
}

.demo-buttons {
  position: fixed;
  z-index: 1;
  left: 1em;
  top: 1em;
}
<div id="overlay">
  <div id="popup">
    <div class="js-popup-content"></div>
  </div>
</div>

<div class="demo-buttons">
  <button class="js-demo-0">Short popup, long content</button>
  <button class="js-demo-1">Long popup, short content</button>
</div>

<div id="content">
  Page content
</div>

© www.soinside.com 2019 - 2024. All rights reserved.