-1

Layout

I have three divs with class "row". Inside of row2 I have two divs with class "layer". I'm trying to set Layer1 and Layer2 on top of eachother, however, when setting them to position:absolute the parent's collapses. Due to the nature of using position:absolute. How can I prevent this from happening?

I've tried the solutions from this thread: How do you keep parents of floated elements from collapsing?

With no success, and I've also tried the "Clearfix" but that doesn't work either.

Code:

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;
}
Community
  • 1
  • 1
slanden
  • 1,199
  • 2
  • 15
  • 35
  • Include your code possibly in code snippet or jsfiddle so people know what you are doing and can modify your code to help your out. – Rikin Feb 13 '17 at 15:04
  • If the parent is collapsing, that means there's nothing in it (that isn't absolutely positioned), thus bringing up my question: Why does Layer 2 need to be "on top" of Layer 1 if Layer 1 has no content? Can you not just put Layer 2 *inside* Layer 1 without a `position: absolute;`? – Tyler Roper Feb 13 '17 at 15:04
  • @Rikin I've added some code, as you can see it's very basic. – slanden Feb 13 '17 at 15:50
  • @Santi the content is irrelevant, although I should have clarified that there will be content in both layers. I simply want them on top of each other and which ever is the biggest layer will stretch the parent to its size. Your solution could very well work, but it would stretch the parent to the first layer and if the second layer is bigger it will just overflow, not stretch the parent. – slanden Feb 13 '17 at 15:54
  • To those who down voted the question... Why? I think I've improved the question and made it as clear as possible, but if something is causing negative votes on my question I need to know how to fix it. – slanden Feb 14 '17 at 20:32

2 Answers2

0

Use position: relative for layer1, put layer2 INTO layer1 and make layer2 position: absolute

Johannes
  • 64,305
  • 18
  • 73
  • 130
-1

try something like this:

#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>
Hemant
  • 1,961
  • 2
  • 17
  • 27
  • Thank you for your answer, however, I don't want to specify a height. It needs to be able to stretch like a normal div. – slanden Feb 13 '17 at 16:01