【问题标题】:Absolute positioning without extending parent不扩展父级的绝对定位
【发布时间】:2019-11-16 11:17:22
【问题描述】:

我正在尝试在包含其他元素的 div 元素中放置一个“搜索器”。我希望搜索者能够在内容 div 之上移动,而无需推动其他内容,同时也跟随滚动条。该区域可调整大小,因此我不能使用恒定的宽度/高度。就像视频编辑器中的搜索器一样。

这是我到目前为止所得到的

#container {
  width: 200px;
  height:100px;
  background-color: gray;
  overflow: scroll;
}

#content {
  width: 300px;
  height: 120px;
}

#box {
  width: 40px;
  height: 40px;
  background-color: green;
}

#seekerContainer {
  position: relative;
  width: 100%;
  height: 100%;
}

#seeker {
  width: 4px;
  height: 100%;
  position: relative;
  background-color: blue;
  left: 10%;
}
<div id="container">
  <div id="content">
      <div id="seekerContainer">
        <div id="seeker"></div>
    </div>
    
    <div id="box"></div>
  </div>
</div>

我已经尝试了不同的组合,让 seekerContainer 和 seeker 的位置是绝对/相对的,但是 seeker 不会跟随滚动,或者它会扩展 div 的高度。

有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    我想这就是你要找的:

    .container {
      width: 200px;
      height: 100px;
      background-color: gray;
      overflow: scroll;
    }
    
    .content {
      height: 500px;
      position: relative;
    }
    
    .box {
      width: 40px;
      height: 40px;
      background-color: green;
    }
    
    .seeker {
      width: 4px;
      height: 100%;
      position: absolute;
      background-color: blue;
      left: 10%;
      top: 0;
    }
    <div class="container">
      <div class="content">
        <div class="seeker"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
      </div>
    </div>

    此外,您不想将id 放在每个元素上并使用id 进行样式设置。您应该为此使用classes。元素的 ID 对于页面必须是唯一的,因此当您需要将相同的样式应用于更多元素时,它不是很有用。

    【讨论】:

      猜你喜欢
      • 2010-11-16
      • 2013-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多