2009-02-23 82 views
28

我正在嘗試爲正在處理的頁面設置一個簡單的水平選項卡結構,並且遇到浮動div與z-index結合的問題。重疊浮動的CSS

查看下面的代碼在瀏覽器中:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>Untitled Document</title> 
    <style type="text/css"> 
     #main { width: 500px; z-index: 1;} 

     .left { float: left; width: 96px; background-color: red; border: 2px solid orange; z-index: 2; margin-right: -2px } 
     .right { float: left; width: 396px; background-color: #09c; border: 2px solid green; z-index: 3; } 

     .clear { clear: both; } 
</style> 
</head> 

<body> 
    <div id="main"> 
     <div class="left"> 
      LEFT 
     </div> 
     <div class="right"> 
      RIGHT 
      <br /> 
      RIGHT 
     </div> 
     <div class="clear"></div> 
    </div> 
</body> 
</html> 

爲什麼不左div的橙色邊框重疊右div的綠色邊框?

回答

60

z-index屬性不適用於靜態定位的元素。爲了使用z-index,CSS還必須包含靜態以外的任何位置值(即相對,絕對,固定)。

.left { float: left; width: 96px; background-color: red; border: 2px solid orange; z-index: 3; margin-right: -2px; position: relative; } 
.right { float: left; width: 396px; background-color: #09c; border: 2px solid green; z-index: 2; position: relative; } 

會給你你想要我想的。我補充說:相對;並將.left的z-index更改爲3(從2開始),並將.right的z-index更改爲2(從3開始)。

7

z-index對元件沒有影響未定位(例如position:absolute;

+2

或`position:relative;` – 2016-04-07 18:49:00

0

margin-left

.right { float: left; width: 396px; background-color: #09c; border: 2px solid green; z-index: 3; margin-left: -5px;} 
0

使用元素upper的position屬性。將position:relative添加到.left