2012-02-23 123 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>