如何让一个div位于另一个div下方

3

我希望在#green div 下方出现 #blue div

#blue div 使用了 margin-top : -10px; 属性

 <style>
    #red{
        width: 400px;

        border: 1px solid red;
    }
    #green{
        width: 100%;
        height: 100px;
        background-color: green;
        border-bottom: 2px solid yellow;
        z-index: 2;
    }
    #blue{
        width: 100%;
        height: 100px;
        background-color: blue;
        border-top: 2px solid brown;
        margin-top: -10px;
        z-index: 1;
    }
    </style>


<div id="red">
    <div id="green">
    </div>
    <div id="blue">
    </div>
</div>

4
你有没有用谷歌搜索过?大约有50个重复的问题。另外,你的代码已经可以工作了。 - dsgriffin
什么问题?http://jsfiddle.net/am9zS/ - Artyom Neustroev
1
我猜在绿色和蓝色div元素中都添加position:relative;应该可以使z-index起作用,但我不确定它是否能在所有浏览器上都良好地工作(我在考虑早期版本的IE ...) - Matt Gibson
2个回答

7

可能将#blue#green div上添加position:absolute,并在#red div上添加position:relative,可以实现您想要的效果,因为我猜测您需要一个位于另一个后面。如果它们需要一个接一个,则在蓝色和绿色上也使用相对定位。


2
请查看此jsfiddle链接:http://jsfiddle.net/eGpUM/,我已在您的以上代码中添加了它。 - Martin Turjak

1
我看不到问题,你的代码没问题。或者你是指在div下面吗?像蓝色div隐藏在绿色div下面?那么你需要在想要移动/隐藏的div上添加position:relative(或absoulte)属性,然后设置top或left。例如:
        #blue{
    /* without position: relative/absoulte the z-index wont work!*/
        position:relative;
/* this moves the dives up or down*/
        top: -100px;
/* this move the div left or right! */
left: 15px;
        width: 100%;
        height: 100px;
        background-color: blue;
        border-top: 2px solid brown;
        margin-top: -10px;
        z-index: 1;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接