相对于块固定的位置,而不是视口

时间:2018-03-15 19:01:35

标签: html css position css-position

我有.gridster项目(块绝对定位,宽度和高度固定,并且有自动溢出),在内部我想要红色块(绝对位于右下角)以保持在他开始的位置,但是当我使用滚动时,红色块跟随滚动。



.gridster-item {
    width: 400px;
    height: 200px;
    position: relative;
    overflow: auto;
    background-color: rgb(204, 214, 249);
}

.resizer {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 10px;
    height: 10px;
    background-color: red;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
</head>
<body>
    <div class="gridster-item">
        <div class="content">
            <p>Lorem Ipsun dolor amet</p>
            <p>Lorem Ipsun dolor amet</p>
            <p>Lorem Ipsun dolor amet</p>
            <p>Lorem Ipsun dolor amet</p>
            <p>Lorem Ipsun dolor amet</p>
            <p>Lorem Ipsun dolor amet</p>
            <p>Lorem Ipsun dolor amet</p>
            <p>Lorem Ipsun dolor amet</p>
            <p>Lorem Ipsun dolor amet</p>
            <p>Lorem Ipsun dolor amet</p>
            <p>Lorem Ipsun dolor amet</p>
            <p>Lorem Ipsun dolor amet</p>
            <p>Lorem Ipsun dolor amet</p>
            <p>Lorem Ipsun dolor amet</p>
            <p>Lorem Ipsun dolor amet</p>
            <p>Lorem Ipsun dolor amet</p>
            <p>Lorem Ipsun dolor amet</p>
        </div>
        <div class="resizer"></div>
    </div>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您需要将{em>包装与position: relative一起使用,以便绝对定位的元素将相对定位到它不受滚动 div的影响:

#wrapper {
  display: inline-block; /* or "inline-flex" which also only takes the content's width */
  position: relative;
}

.gridster-item {
  width: 400px;
  height: 200px;
  /*position: relative;*/
  overflow: auto;
  background-color: rgb(204, 214, 249);
}

.resizer {
  position: absolute;
  bottom: 0;
  right: 17px; /* 17px because that's a typical width of the scrollbar */
  width: 10px;
  height: 10px;
  background-color: red;
}
<div id="wrapper">
  <div class="gridster-item">
    <div class="content">
      <p>Lorem Ipsun dolor amet</p>
      <p>Lorem Ipsun dolor amet</p>
      <p>Lorem Ipsun dolor amet</p>
      <p>Lorem Ipsun dolor amet</p>
      <p>Lorem Ipsun dolor amet</p>
      <p>Lorem Ipsun dolor amet</p>
      <p>Lorem Ipsun dolor amet</p>
      <p>Lorem Ipsun dolor amet</p>
      <p>Lorem Ipsun dolor amet</p>
      <p>Lorem Ipsun dolor amet</p>
      <p>Lorem Ipsun dolor amet</p>
      <p>Lorem Ipsun dolor amet</p>
      <p>Lorem Ipsun dolor amet</p>
      <p>Lorem Ipsun dolor amet</p>
      <p>Lorem Ipsun dolor amet</p>
      <p>Lorem Ipsun dolor amet</p>
      <p>Lorem Ipsun dolor amet</p>
    </div>
    <div class="resizer"></div>
  </div>
</div>