2012-02-23 70 views
0

我有以下代碼:如何向上移動內部盒子並使用CSS保留外部盒子?

<html> 
<head> 
<style> 
#yellow {height:100px; background:yellow;} 
#blue {background:blue;} 
#red {background:red; width: 400px; height: 100px; margin:0px auto;} 
</style> 
</head> 
<body> 
     <div id="yellow"></div> 
     <div id="blue"> 
       <div id="red">Lots of content goes in here that will expand the outer blue box as well</div> 
     </div> 
</body> 
</html> 

我想要的紅色框,以便它重疊的黃色盒子和藍盒子都向上移動約30像素。當我試圖做一個#red {margin:-30px auto 0px auto;}時,藍色盒子也隨着紅色盒子向上移動了30個像素,儘管我想讓藍色盒子保持原位。

我如何讓紅框向上移動並重疊黃色和藍色?

回答

1

你在這裏。

#yellow { 
    height:100px; 
    background:yellow; 
} 
#blue { 
    background:blue; 
} 
#red { 
    background:red; 
    width: 100px; 
    height: 100px; 
    margin:0px auto; 
    position:relative; 
    top:-30px; 
} 
+0

如果您不希望#blue底部的空格,請將margin-bottom:-30px添加到#red。 – 2012-02-23 21:25:01

1

你可以嘗試使用position: relative

#red { 
    position: relative; 
    top: -30px; 
    /* other CSS */ 
} 
1

在你的情況下,藍色框包圍的紅色方塊。所以你必須相對定位紅色方塊。

因此,您只需將以下一段CSS代碼添加到#red id。

​​

這是根據您的預期結果的代碼;

<html> 
<head> 
<style> 
#yellow {height:100px; background:yellow;} 
#blue {background:blue;} 
#red {background:red; width: 400px; height: 100px; margin:0px auto; position: relative; top: -30px;} 
</style> 
</head> 
<body> 
     <div id="yellow"></div> 
     <div id="blue"> 
       <div id="red">Lots of content goes in here that will expand the outer blue box as well</div> 
     </div> 
</body> 
</html>