可滚动父级上的绝对定位元素

时间:2016-01-28 12:52:32

标签: html css css-position

我正在尝试将父元素的子元素(类似于工具栏)定位在其底部边缘。行为应与使用浏览器视图固定的位置相同。

我现在正在使用绝对位置。在父母需要滚动内容之前,一切都很完美。然后工具栏与父母内容的其余部分一起移动。

有人能解释一下工具栏移动的原因吗? 是否有可能在不需要任何javascript的情况下实现该任务?

* {
  box-sizing: border-box;
}

.container {
  position: relative;
  width: 100px;
  height: 150px;
  overflow-y: auto;
  border: 1px solid black;
}

.mock {
  height: 200px;
  background-color: red;
}

.tool-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 40px;
  background-color: blue;
}
<div class="container">
  <div class="mock"></div>
  <div class="tool-bar"></div>
</div>

2 个答案:

答案 0 :(得分:1)

工具栏位于可滚动区域内,这就是它滚动的原因。试试这段代码:

<强> HTML

<div class="container">
  <div class="scroll">
    <div class="mock"></div>
  </div>

  <div class="tool-bar"></div>
</div>

<强> CSS

div.scroll { /* style of .container to scroll */ }

答案 1 :(得分:0)

我找到了一个可能对你有帮助的小提琴。他们使用position:fixed并且div不是嵌套的:

http://jsfiddle.net/b2jz1yvr/

<div class="fixedContainer">
    This is experimental
</div>
<div class="otherContainer"></div>

.fixedContainer {
    background-color:#ddd;
    position: fixed;
    padding: 2em;
    left: 50%;
    top: 0%;
    transform: translateX(-50%);
}

.otherContainer {
    height:1000px;
    background-color:#bbb
}