CSS 设置相对于浏览器窗口大小的最大高度,而不是主体大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28948894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 03:03:27  来源:igfitidea点击:

Setting max-height relative to browser window size, not body size

css

提问by jovan

I have a modal popup box on my site, inside the <body>tag.

我的网站上有一个模态弹出框,位于<body>标签内。

This is the styling of the popup:

这是弹出窗口的样式:

.modalbox {
    text-shadow: none;
    position: absolute;
    padding: 22px;
    left: 50%;
    background: white;
    z-index: 90;
    border-radius: 6px;
    display: none;
    font-size: 14px;
    width: 80%;
}

Setting the width is simple. However, the vertical content is dynamic and therein my problem lies - I don't want the box to be taller than the browser window.

设置宽度很简单。但是,垂直内容是动态的,我的问题就在于此 - 我不希望框比浏览器窗口高。

I've tried setting max-width: 90%;, and this works if the bodyof the page is not longer vertically than the browser window.

我试过设置max-width: 90%;,如果body页面的垂直长度不长于浏览器窗口,这会起作用。

However, when the bodyoverflows (and scrollbars appear), then the 90%maximum height above is relative to the height of the body, not the window. This means that the modal box can overrun out of the window vertically, forcing the user to scroll the page to see its full content.

但是,当body溢出(和滚动条出现)时,90%上面的最大高度是相对于 的高度,而body不是窗口的高度。这意味着模式框可以垂直超出窗口,迫使用户滚动页面以查看其完整内容。

What I want to accomplish is for that max height to be 90% of the browser windowso that the entire modal box is visible at all times.

我想要完成的是最大高度为浏览器窗口的90%,以便整个模式框始终可见。

I will handle overflow, I just need help figuring out how to restrict the vertical size in the way described above.

我将处理溢出,我只需要帮助弄清楚如何以上述方式限制垂直大小。

采纳答案by Ryguy

There isn't a way to do this with html or css as far as I know, you'd have to accomplish this using JQuery:

据我所知,没有办法用 html 或 css 来做到这一点,你必须使用 JQuery 来完成:

http://api.jquery.com/height/

http://api.jquery.com/height/

// Returns height of browser viewport

$( window ).height();

and then just use whatever 90% of the height value is.

然后只使用高度值的 90%。

回答by Michael Schmid

Use the viewport-percentage lengths.

使用视口百分比长度

The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.

视口百分比长度与初始包含块的大小有关。当初始包含块的高度或宽度发生变化时,它们会相应地缩放。

.modalbox {
    max-height: 90vh; }