2015-10-20 99 views
0

我想設置一個固定在父div內的div位置。 當我將固定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

+0

使用保證金,如果你希望它尊重其當前位置來定位固定股利。 – Aaron

+0

使用絕對位置而不是固定位置。 –

+0

對於你想要做的事情可能有一個解決方法,但你需要更好地解釋你的需求,並提供一個合適的代碼示例。 –

回答

0

使用帶有邊距的固定位置將允許您將元素相對於其父元素進行定位。

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

運行片斷全屏查看!

+0

完美!謝謝:) – jamie

+0

不客氣:) – Aaron

0

固定定位僅適用於根元素(HTML),而不是任何父元素。如果你想在父元素中定位一些東西,可以使用position:absolute,並確保父元素的位置是:relative(或者position:absolute)。

+0

謝謝 但固定的div應該滾動頁面內的父div – jamie

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