html - 空白 : nowrap seems to affect inner elements position: absolute

标签 html css

我想要一个水平的元素列表,包含在一个具有固定宽度的可水平滚动的外部包装器中。外包装有一个相对位置。其中一项包含绝对定位的 div。

滚动外包装时,我希望绿色覆盖层保持在同一位置。我认为 position: absolute 总是相对于具有定义位置的第一个祖先(这将是外部包装器)?

我正在使用 white-space: nowrap 为 #wrapper 获取一行中的元素。

#outer-wrapper {
  position: relative;
  width: 300px;
  height: 150px;
  overflow: scroll;
}

#wrapper {
  white-space: nowrap;
  display: inline-block;
}

#one {
  background-color: red;
}

#two {
  background-color: blue;
}

.box {
  white-space: normal;
  display: inline-block;
  width: 200px;
  height: 150px;
}

.overlay {
  background-color: green;
  position: absolute;
  bottom: 0px;
  left: 0px;
  width: 100%;
  height: 40px;
}
<div id="outer-wrapper">
  <div id="wrapper">
    <div id="one" class="box">
      <div class="overlay"></div>
    </div>
    <div id="two" class="box"></div>
  </div>
</div>

我希望标记保持示例中的原样,尽管这并不是完全固定的。

而且我真的无法为水平列表定义固定宽度。

最佳答案

如果我没猜错你的问题,那么只用 HTML 和 CSS 是不可能的。然而,您可以使用 jQuery 实现它,如下所示:

$(function() {
  var wrapper = $('#outer-wrapper');
  
  $('#outer-wrapper').scroll(function() {
    $('.overlay').css({
      'marginLeft': wrapper.scrollLeft()
    });
  });
});
#outer-wrapper {
  position: relative;
  width: 300px;
  height: 150px;
  overflow: scroll;
}

#wrapper {
  white-space: nowrap;
  display: inline-block;
}

#one {
  background-color: red;
}

#two {
  background-color: blue;
}

.box {
  white-space: normal;
  display: inline-block;
  width: 200px;
  height: 150px;
}

.overlay {
  background-color: green;
  position: absolute;
  bottom: 0px;
  left: 0px;
  width: 100%;
  height: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="outer-wrapper">
  <div id="wrapper">
    <div id="one" class="box">
      <div class="overlay"></div>
    </div>
    <div id="two" class="box"></div>
  </div>
</div>

关于html - 空白 : nowrap seems to affect inner elements position: absolute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38395189/

相关文章:

javascript - 键盘布局的 JS 颜色更改

css - 为什么有些网页呈现不流畅

javascript - Jquery 仅在播放视频时有效

javascript - 鼠标移出时隐藏菜单

css - 将 CSS 应用于 JQGrid 中的表格单元格(td)?

html - 使用非正统的 `head {display: block}` 向用户显示文本?

html - 表内的绝对元素导致表启用 overflow-y : scroll somehow

javascript - Jquery 循环 : iterate siblings by four, 然后从头开始

css - 如何将导航移至屏幕右侧?

javascript - 光滑的 slider 自动播放不起作用