Search code examples
htmlcsscss-positionfixed

position fixed inside parent div


i'm trying to set a div positiong fixed inside a parent div. When i set the fixed div to top 0, it is on the top of the body.

The fixed div should be scroll with the page

here is my code example:

    <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


Solution

  • Using position fixed with margin will allow you to position the element in respect to its parent.

    * {
      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>

    Run the snippet in full screen to view!