Overflow with absolute/relative positioning layout

落爺英雄遲暮 提交于 2019-12-01 16:39:47

问题


for quite some time I'm fiddling around with a specific layout matter that I'm obviously approaching the wrong way.

Here is the approach broken down to its basic components:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="stretched">
    <div class="header">SOME HEADER</div>
    <div class="someControls">
        <input type="button" value="click me"/>
        <input type="button" value="no me"/>
    </div>
    <div class="inner">
        some text...
    </div>
</div>
</body>
</html>

with the following css:

.stretched {
    position:absolute;
    height:auto;
    bottom: 0;
    top: 0;
    left: 0;
    right: 0;
    width: 250px;
    margin: 30px auto 20px;
    background-color: green;
}

.inner {
    margin:10px;
    background-color: red;   
    overflow: auto;        
}

​What I'm trying to do is having the stretched div utilizing all available vertical viewport space (minus a few pixels above and below for header and footer) and being centered horizontally with a fixed with.

This seems to work pretty well. The problem is that the overflow: auto; property is not applied to the inner content as I want it to. When some text... gets longer, the inner div overlaps my container and shows no scrollbars.

Here's the Fiddle: fiddle #1

I want to avoid having scrollbars on the page body and instead having the overflow managed by scrollbars inside the inner div, thus making stretched always entirely visible.

I could apply the same trick with position: absolute; top: 0; ... to the inner div as well, but then I have to specify the height of header + someControls explicitly, which I want to avoid, because it is different on all my pages.

This is how it works like I want it to (except for the part top: 40px;): fiddle #2

What am I doing wrong here? Thanks in advance!


回答1:


I don't think this is possible with pure CSS (..that works in all common browsers).

Here's an approach using the old Flexbox spec: http://jsfiddle.net/thirtydot/xRr7e/

Unfortunately, it only works in WebKit browsers/Firefox.

It's time to use a few lines of JavaScript for this layout..




回答2:


Remove

position: absolute;

and add

border: 10px solid green;

http://jsfiddle.net/Rpdr9/367/

EDIT: If you dont like huge border, you can change the border-size to 1px.

border: 1px solid green;

Even this works.




回答3:


Hey why are define position absolute in your style sheet

replace this one

    .stretched {

    width: 250px;
    margin: 30px auto 20px;
    background-color: green;
}

Live demo http://jsfiddle.net/rohitazad/Rpdr9/366/

Updated js fiddle http://jsfiddle.net/rohitazad/Rpdr9/368/



来源:https://stackoverflow.com/questions/10294543/overflow-with-absolute-relative-positioning-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!