簡體   English   中英

div始終位於固定元素的頂部

[英]div always on top of fixed element

我想做的很簡單。 我的頁面底部有固定的div。 它必須始終顯示在底部,因此使用固定位置。

在這個div中,有2個div,其中一個必須始終位於此固定div的頂部,另一個必須是可滾動的。

問題是小div,如果我給他固定的位置,那是在窗口頂部的位置,而不是在此固定div的位置,正如您在此小提琴中看到的那樣

如果小div是絕對位置,則它位於固定div的頂部,但是如果滾動,則可以在此小提琴中看到

HTML

<div class="bottom">
 <div class="top"></div>
 <div class="content"></div>
</div>

CSS

.bottom
{
    padding:20px;
    height: 253px; 
    position: fixed; 
    bottom:0px;
    width:100%;
    background-color: red;
    overflow-x: hidden;
    overflow-y: scroll;
}

.top
{
    height:50px;
    width:100%;
    background-color: yellow;
    position: fixed;
    top: 0px;
}

.content
{
    height: 1500px;
    background: linear-gradient(green, blue);
}

是否可以在不觀看jvascript滾動的情況下進行這項工作? 通過純CSS?

您可以對內容使用包裝器<div>並使其滾動-這樣,絕對定位的兄弟姐妹就不會隨之滾動,如下所示:

HTML

 <div class="bottom">
   <div class="top"></div>
      <div class='contentWrap'>
        <div class="content"></div>
      </div>
 </div>

CSS

.contentWrap{
 height:100%;
 overflow-y:auto;
}

 * { margin: 0; padding: 0; } .bottom { padding: 20px; height: 253px; position: fixed; bottom: 0px; width: 100%; background-color: red; overflow: hidden; } .top { height: 50px; width: 100%; background-color: yellow; position: absolute; top: 0px; } .contentWrap { height: 100%; padding-top: 30px; /* .top height - .bottom padding*/ overflow-y: auto; } .content { height: 1500px; background: linear-gradient(green, blue); } 
 <div class="bottom"> <div class="top"></div> <div class='contentWrap'> <div class="content"></div> </div> </div> 

JSFiddle演示

您使用fixed-> absolute的方法是絕對正確的,因為您可以通過定位將元素定位為絕對但相對於其父元素。 問題在於,絕對.top始終出現在.bottom的頂部-因此,如果滾動.bottom,則.top會緊隨其后。

我的解決方案將使用position:fixed; 在.top上,但使用bottom而不是top:

.top {
    ....
    position:fixed;
    bottom:253px; /*note sure how it should look at the end, try it yourself*/
 }

添加div帶班topdiv與類content ,並刪除top:0.top類:

HTML

<div class="bottom">  
    <div class="content" >
        <div class="top"></div>
    </div>
<div>

CSS

.top
{
    height:50px;
    width:100%;
    background-color: yellow;
    position: fixed;
}

小提琴

嘗試一下,它基本上只是在可滾動div周圍放置一個框架容器,以將所有內容保持在原位。 的jsfiddle

<div class="bottom">
    <div class="top"></div>
    <div class="scroll-container">
        <div class="content" ></div>
    </div>
<div>

.scroll-container 
{
    height: 203px;
    overflow-y: scroll;
}

另外,刪除overflow-y: scroll; 來自.bottom

如果您已經處理了固定的高度和位置,為什么不只將“頂部”部分也固定好呢? 像這樣檢查Fiddle演示

.top
{
    height:50px;
    bottom:243px;
    width:100%;
    background-color: yellow;
    position: fixed;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM