堆叠子元素没有折叠父元素

时间:2017-02-13 14:57:52

标签: html css

Layout

我有三个div和#34; row"。在row2里面,我有两个div,类#34; layer"。我尝试将Layer1和Layer2设置在彼此之上,但是,当将它们设置为position:absolute时,父级会崩溃。由于使用position:absolute的性质。我怎样才能防止这种情况发生?

我已尝试过此主题的解决方案: How do you keep parents of floated elements from collapsing?

没有成功,我也尝试过" Clearfix"但那也不起作用。

代码:

HTML

<div id="row1" class="row">
<div id="row2" class="row">
    <div id="layer1" class="layer">
    <div id="layer2" class="layer">
</div>
<div id="row3" class="row">

CSS

.row::after 
{
    content: "";
    clear: both;
    display: block;
}
.layer
{
    position: absolute;
}
.layer::after 
{
    content: "";
    clear: both;
    display: block;
}

2 个答案:

答案 0 :(得分:0)

position: relative用于layer1,将layer2放入INTO layer1并生成layer2 position: absolute

答案 1 :(得分:0)

尝试这样的事情:

#row{
  positon:relative;
  width:100%;
  height:300px;
  background:green;
  }
.layer{
 


  
  }
.layer1{
   position:absolute;
  background:blue;

    width:50%;
height:200px;
}
.layer2{
   position:absolute;
  background:yellow;
    width:50%;
  top:40px;
height:100px;
}
<div id="row">
<div class="layer1 ">layer1</div>
<div class="layer2 ">layer2</div>

</div>