当父div的水平滚动可见时,如何在顶级div上显示子div

时间:2018-08-06 07:11:10

标签: html css html5 css3 overflow

我正在尝试显示一个父div高度为100%的子div 当父div的水平滚动可见时。尽管最初看起来确实很简单,但是一直都在努力。

这是标记https://codepen.io/ambarbs/pen/OwwojV

.parent {
  background: grey;
  height: 100px;
  width: 200px;
  overflow-x: auto;
  overflow-y: hidden;
  color: white;
  /*   z-index: 0; */
}

.child {
  width: 400px;
}

.menu {
  height: 300px;
  background: orange;
  z-index: 500;
}
<div class='parent'>
  <div class='child'>
    I want to show the orange .menu DIV on top of this DIV.
    Is it possible when the horizontal scroll is visible?
  </div>
  <div class='menu'></div>
</div>

更新菜单实际上是一个上下文菜单,并且应该始终以理想的方式显示在滚动条的顶部。

2 个答案:

答案 0 :(得分:0)

使用CSS可以通过以下方式实现:

  • .parent设置为position: relative;
  • .child设置为position: absolute;
  • .menu设置为position: sticky; left: 0;

.parent {
  position: relative;
  height: 100px;
  width: 200px;
  overflow-x: auto;
  overflow-y: hidden;
}

.child {
  position: absolute;
  width: 400px;
}

.menu {
  position: -webkit-sticky;
  position: sticky;
  left: 0;
  width: inherit;
  height: inherit;
  background: rgb(255, 120, 0, 0.8);
}
<div class='parent'>
  <div class='child'>
    I want to show the orange .menu DIV on top of this DIV.
    Is it possible when the horizontal scroll is visible?
  </div>
  <div class='menu'>MENU</div>
</div>

请注意,粘性位置not supported by any IE浏览器(当然)


针对IE 9、10、11的解决方案

一些JS可以帮助您处理较旧的浏览器。
基本上,在滚动时,它使用translateX来设置.menu的位置:

const transX = (ev, el) => {
  ev.target.querySelector(el).style.transform = `translateX(${ev.target.scrollLeft}px)`;
};

document.querySelector(".parent").addEventListener("scroll", ev => transX(ev, ".menu"));
.parent {
  position: relative;
  height: 100px;
  width: 200px;
  overflow-x: auto;
  overflow-y: hidden;
}

.child {
  position: absolute;
  width: 400px;
}

.menu {
  position: relative; /* Set to "sticky" and remove JS if you don't care about IE */
  left: 0;
  width: inherit;
  height: inherit;
  background: rgb(255, 120, 0, 0.8);
}
<div class='parent'>
  <div class='child'>
    I want to show the orange .menu DIV on top of this DIV.
    Is it possible when the horizontal scroll is visible?
  </div>
  <div class='menu'>MENU</div>
</div>

答案 1 :(得分:-1)

Solution

将所需子级的position属性设置为fixed。这样,其位置将基于浏览器窗口而不是父窗口。对于没有内容的fixed <div>,必须指定widthheight属性。如果您希望宽度与父宽度相同,则可以使用inherit值。

.menu{
  position: fixed;
  height: 300px;
  width: inherit;
  background: orange;
  left: 10px;
  top: 10px;
}