Search code examples
cssposition

css position with percent


I have a problem with position divs relative in an other div.

I want to make a div that is position in the horizontal middle of the screen and in this div I want to place 3 other div with the same height. But all of them should be responsive.

A picture says more than words :)

enter image description here

<div id="zwrapper">
 <div id="z1" class="row"></div>
 <div id="z2" class="row"></div>
 <div id="z3" class="row"></div>
</div>

The blu element is the HTML

html{
  background: steelblue;
  height: 100%;
  width: 100%;
  top:0; left:0; bottom: 0; right:0;
}

The lime one ist that div (#zwrapper) where I want to add the three red divs.

#zwrapper{
  height: 81%;
  top: 10%;
  width: 100%;
  left: 0;
  position: absolute;
  background: lime;
}

The red divs make problems. All divs have a height of 30%. The first one should be aligned to top and the third to bottom. The middle div with the id #z2 is the only one which get a margin of 5%.

.row{
  position: relative;
  width: 80%;
  background: red;
  height: 30%;
 }
 #z2{
  margin: 5% 0;
 }

My idea was to put the 3 divs with a height of 30% into the wrapper and give the middle one a margin (top / bottom) of 5% so I get a height of 100%. But this does not work.

If I resize the window in width, the height of the red divs changes though I don't change the height.

I make a fiddle to demonstrate this. http://jsfiddle.net/ELPJM/

Thanks in advance


Solution

  • The problem is that percent values in margin are always relative to width, not height. You can achieve this by using absolute positioning instead, and setting a "top" value on each row. Like this:

    .row {
        position: absolute;
        width: 80%;
        background: red;
        height: 30%;
    }
    
    #z1 {
        top: 0%;
    }
    
    #z2 {
        top: 35%;
    }
    
    #z3 {
        top: 70%;
    }
    

    http://jsfiddle.net/ELPJM/8/