【问题标题】:position fixed inside parent div固定在父 div 内的位置
【发布时间】:2015-10-20 08:45:32
【问题描述】:

我正在尝试设置一个固定在父 div 内的 div 位置。 当我将固定 div 设置为 top 0 时,它位于 body 的顶部。

固定的div应该随页面滚动

这是我的代码示例:

    <div class="container">

    <div class="col-sm-8">
        <p>content</p>
    </div>

    <div class="col-sm-4">                  
        <div id="sidebar">
            <div class="inner">
                <ul>
                <li>link</li>
                <li>link</li>
                <li>link</li>
                <li>link</li>
                </ul>
            </div>
        </div>                
    </div>

</div>

<style>

.container {
    width: 1170px;
    display: table;
}

.col-sm-8, col-sm-4 {
    position: relative;
    float: left;
}

.inner {
    position: fixed;
    top: 0;
}

</style>

example screen layout

【问题讨论】:

  • 如果您希望固定 div 尊重其当前位置,请使用边距来定位它。
  • 使用绝对位置而不是固定位置。
  • 对于您想要做的事情可能有一种解决方法,但您需要更好地解释您的需求,并提供适当的代码示例。
  • 目前还不可能,但听起来你需要position:sticky,但我相信这只是目前的FF。 - developer.mozilla.org/en-US/docs/Web/CSS/position

标签: html css css-position fixed


【解决方案1】:

使用带边距固定的位置将允许您相对于其父元素定位元素。

* {
  height: 2000px;
}
section {
  width: 600px;
  margin: 100px auto;
}
div {
  width: 70%;
  background: grey;
  float: left;
}
aside {
  width: 30%;
  background: orange;
  float: right
}
.inner {
  position: fixed;
  width: 100px;
  height: 60px;
  background: red;
  margin: 100px 0 0 40px;
}
<section>
  <div></div>
  <aside>
    <div class="inner"></div>
  </aside>
</section>

全屏运行 sn-p 即可查看!

【讨论】:

    【解决方案2】:

    固定定位仅适用于根元素 (html),不适用于任何父元素。如果您想在父元素中定位某些内容,请使用 position:absolute 并确保父元素具有 position:relative(或 position:absolute)。

    【讨论】:

    • 谢谢但是固定的div应该随着父div内的页面滚动
    【解决方案3】:

    你的 html 应该是:

    <section>
      <div></div>
      <fixed>
        <div class="inner"></div>
      </fixed>
    </section>
    

    你的css应该是:

    * {
      height: 2000px;
    }
    section {
      width: 600px;
      margin: 100px auto;
    }
    div {
      width: 70%;
      background: #333;
      float: left;
    }
    fixed {
      width: 30%;
      background: green;
      float: right
    }
    .inner {
      position: fixed;
      width: 100px;
      height: 60px;
      background: red;
      margin: 100px 0 0 40px;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-17
      • 2015-12-30
      • 1970-01-01
      • 2011-12-12
      • 2017-06-03
      相关资源
      最近更新 更多