jamie
jamie

Reputation: 47

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

Upvotes: 1

Views: 3257

Answers (3)

Sirat Binte Siddique
Sirat Binte Siddique

Reputation: 453

your html should be :

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

and your css should be :

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

Upvotes: 0

Aaron
Aaron

Reputation: 10430

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!

Upvotes: 1

Mike S.
Mike S.

Reputation: 951

Fixed positioning only applies to the root element (html) and not any parent elements. If you want to position something within a parent element, use position:absolute and make sure that the parent element has position:relative (or position:absolute as well).

Upvotes: 0

Related Questions