div中带有滚动条的div,位置为:fixed

Ein*_*son 40 css css-position

我有一个div位置:固定这是我的容器div为一些菜单.我把它设置为顶部:0px,底部:0px以始终填充视口.在div里面我想要另外两个div,其中较低的一行包含很多行并且有溢出:auto.我希望它将包含在容器div中,但如果有太多行,它只是扩展到固定div之外.下面是我的代码和截图,以澄清:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>MyPlan</title>
    <meta name="X-UA-COMPATIBLE" value="IE=8" />
    <style type="text/css">
        #outerfixed { position:fixed;  width:200px;  background-color:blue; padding:5px; top:0px; bottom:30px;}
        #innerstatic1 { width:100%; background-color:yellow; height:100px;}
        #innerstatic2 { overflow:auto; background-color:red; width:100%;}
    </style>
</head>
<body>
    <div id="outerfixed">
        <h3>OUTERFIXED</h3>
        <div id="innerstatic1">
            <h3>INNERSTATIC1</h3>
        </div>
        <div id="innerstatic2">
            <h3>INNERSTATIC2</h3>
            line<br />
                        ...lots of lines
            line<br />
        </div>
    </div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

替代文字

我有什么方法可以做到这一点吗?同样,我想#innerstatic2进行适当包含#outerfixed内,并得到滚动条,如果它变得比它里面#outerfixed空间较大.

我知道有一些possibilites也通过固定#innerstatic2破解解决这个问题,但我真的很喜欢它是流中可能的话里面#outerfixed,所以如果我搬到什么地方#outerfixed,内部元件会随之而来.

编辑:我知道我可以设置溢出:在#outerfixed汽车,并获得整个事情的滚动条,但我特别希望只是#innerstatic2一个滚动条,这是一个网格,我想滚动只是电网.

任何人?可能?

Dav*_*mas 42

这有一个两步解决方案,但它需要付出一些代价:

  1. 添加overflow-y: scroll;到CSS中#innerstatic2.
  2. 定义height(或max-height)为#innerstatic2,否则它不会溢出,它只会不断增加其高度(默认为divheight: auto).


编辑,因为我有时无法阻止自己.

我在jsbin上发布了一个演示来展示这个的jQuery实现,它将height为你计算一个(它不是通用的,所以它只适用于你当前的html).

(function($) {
  $.fn.innerstaticHeight = function() {
        var heightOfOuterfixed = $('#outerfixed').height(),
        offset = $('#innerstatic2').offset(),
        topOfInnerstatic2 = offset.top,
        potentialHeight = heightOfOuterfixed - topOfInnerstatic2;

        $('#innerstatic2').css('height',potentialHeight);
  }
})(jQuery);

$(document).ready(
    function() {
        $('#innerstatic2').innerstaticHeight();
    }
);
Run Code Online (Sandbox Code Playgroud)


Ofi*_*r D 18

我通过给出ul和身高100%的绝对位置来解决它

ul {
  overflow-y: scroll;
  position: absolute;
  height: 100%;
}
Run Code Online (Sandbox Code Playgroud)

看看这个FIDDLE

  • 此解决方案隐藏了 `ul` 的下端(它不显示最后一个 `li` 实例) (3认同)

小智 6

overflow-y:scroll;

并将其添加到iOS设备。使用触摸确实可以提供更好的滚动效果。溢出-y需要滚动!出于安全原因。自动不会为某些人工作。或至少就是我所听到的。

-webkit-overflow-scrolling: touch;


Ale*_*tin 1

容器div 必须具有overflow:auto 属性。在这种情况下,#outerfixed div