2014-03-24 62 views
0

爲什麼相對定位的div覆蓋固定位置的div?爲什麼相對定位的div覆蓋固定div?

下面是一個例子:

HTML(與相對固定的div包裝內容)

<div id="topheading"> 
    Example Example Example Example Example Example Example Example 
</div> 
<div class="main"> 
<div class="centerpage"> 
     <div class="contentbox1"> 
      Test 
     </div> 
     <div class="contentbox1"> 
      Test 2 
     </div> 
     <div class="contentbox1"> 
      Test 3 
     </div> 
</div> 
</div> 

CSS

#topheading { 
    position: fixed; 
    top: 0px; 
    left: 0px; 
    height: 58px; 
    width: 100%; 
    background-color: rgba(194, 194, 194, .5); 
} 

.main { 
    position: relative; 
    width: 100%; 
} 

.centerpage { 
    width: 99%; 
    background: #ccc; 
    overflow: hidden; 
    margin-top: 62px; 
    margin-bottom: 2px; 
    margin-left: auto; 
    margin-right: auto; 
} 

.contentbox1 { 
    float: left; 
    width: 99%; 
    background: #448; 
    min-height: 200px; 
    border: solid black 2px; 
} 

JSFiddle

固定定位的div變成被覆蓋向下滾動時相對定位的div;怎麼來的?

+0

可能重複(http://stackoverflow.com/questions/6314193/css-positioning-relative-over-fixed-absolute) – cubrr

+0

添加'的z-index: 1'到'#topheader'的CSS屬性:) – cubrr

回答

0

我相信這是因爲div的z-index是由它們被解析的順序隱式設置的。也就是說,

<div class="main"> 
    <div class="centerpage"> 
     <div class="contentbox1"> 
      Test 
     </div> 
     <div class="contentbox1"> 
      Test 2 
     </div> 
     <div class="contentbox1"> 
      Test 3 
     </div> 
    </div> 
</div> 
<div id="topheading"> 
    Example Example Example Example Example Example Example Example 
</div> 

似乎解決你的問題。

編輯:雖然,正如其他人所說,解決這個問題的更具表現力的方法是使用z-index。

#topheading { 
    position: fixed; 
    top: 0px; 
    left: 0px; 
    height: 58px; 
    width: 100%; 
    background-color: rgba(194, 194, 194, .5); 
    z-index:1; 
} 
[CSS定位相對在固定/絕對]的