位置固定在父div之内

时间:2015-10-20 08:45:32

标签: html css css-position fixed

我试图在父div中设置一个div positiong。 当我将固定div设置为顶部0时,它位于正文的顶部。

固定的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

3 个答案:

答案 0 :(得分: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>

全屏运行代码段进行查看!

答案 1 :(得分:0)

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

答案 2 :(得分:0)

你的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;
}
相关问题