简体   繁体   English

如何创建具有百分比高度的固定的可滚动div?

[英]How to create fixed, scrollable div with percentage height?

I am trying to create a fixed div in the middle of a page that is scrollable, but I'm not able to get the div to scale to the page size properly. 我试图在可滚动页面的中间创建一个固定的div,但是我无法使div正确缩放到页面大小。 It's set to take 70% of the page (AKA, stopping around 20px from the bottom of the browser) but when you make the height of the browser less, it doesn't seem to react properly. 它被设置为占据页面的70%(又名,距离浏览器底部约20像素),但是当您减小浏览器的高度时,它似乎无法正常响应。

I can't seem to figure out why this is, suspect it's related to fixed positioning a div and then attempting to use a percentage height but I am sure there is a way around it. 我似乎无法弄清楚为什么会这样,怀疑它与固定放置div有关,然后尝试使用百分比高度,但是我敢肯定有办法解决。

To see what I mean, there is an example website here for this. 要明白我的意思,有一个例子网站在这里这一点。 Drag the window up from the bottom and eventually the div does not resize anymore. 从底部向上拖动窗口,最终div不再调整大小。 :( :(

The CSS for the div is: div的CSS是:

.singlepost {
position: fixed;
height: 70%;
background-color: white;
padding-left: 10px;
padding-right: 10px;
overflow-x: hidden;
}

And the structure of the HTML is: HTML的结构是:

<div class="container">
    <div class="container">
     [This is the fixed width box I want to size]
    </div>
</div>

One idea I had was to use javascript to determine the height of the browser dynamically and set the fixed with to a specific pixel height but I doubt that's the best way to solve this. 我曾经有一个想法是使用javascript动态确定浏览器的高度,并将固定值设置为特定的像素高度,但是我怀疑这是解决此问题的最佳方法。

Your page is calculating the height of the .singlepost div correctly. 您的页面正在正确计算.singlepost div的高度。 It is always 70% and it is adjusting when the page height gets smaller. 它始终为70%,并且在页面高度变小时进行调整。

The problem is the .singlepost div sits after some content that is a fixed height. 问题是.singlepost div位于固定高度的某些内容之后。 So when the content above the .singlepost div is greater than 30% of the page height, the .singlepost div does not exceed the bottom of the page. 因此,当.singlepost div上方的内容大于页面高度的30%时, .singlepost div不会超过页面底部。 But when you make the page height smaller, the top content gets less than 30% of the page, and at that point the bottom of the .singlepost div will drop under the bottom of the page. 但是,当您减小页面高度时,顶部内容将不到页面的30%, .singlepost div的底部将降至页面底部。

Rather than setting the height, you can set the top and bottom: 您可以设置顶部和底部,而不是设置高度:

CSS CSS

.singlepost {
    position: fixed;
    background-color: white;
    padding-left: 10px;
    padding-right: 10px;
    overflow-x: hidden;
    top: 270px;
    bottom: 20px;
}

This assumes that your top content is 270px high. 假设您的最高内容为270px高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM