Skip to content Skip to sidebar Skip to footer

How Do I Stack Div Elements On Top Of Each Other With Position: Relative

I'm having a problem getting div elements to stack on top of each other vertically. I have a mainwrapper and 2 div elements inside them that I need to be stacked. But whenever I gi

Solution 1:

Would http://jsfiddle.net/uFf9D/ work?

I commented out the dimensions on .wrapper and added overflow: hidden. Then changed .test1 and .test2 to position: relative and float: right.

Edit: Readded the width since it's needed for centering.

.wrapper {
  width: 605px;
/*
  height: 240px;
*/overflow: hidden;
  ...
}

.test1 {
/*
  position: relative;
*/float: right;
  ...
}

.test2 {
  position: relative;
  float: right;
  ...
}

If you want to skip the floats and overflow: hidden, direction: rtl might be a possible solution on .wrapper.. don't know if it works or whether it's inherited.

Try out this addition to .test2 to fill up .test1:

width: 100%;
box-sizing: border-box;
-moz-box-sizing: border-box;

Solution 2:

I'm not entirely sure why you were positioning those like you were. I'm going to assume you were using position: absolute so that those divs wouldn't intervene with other content. Also, there's no need to put 'display: block' for divs, that's their default value.

Here's a fiddle that does as you pleased, and the wrapper is set to position: absolute so that those divs don't intervene with other content. Basically, you'd use the wrapper as a frame. Solution

.wrapper {
    width: 605px;
    left: 50%;
    margin-left: -302.5px;
    position: absolute; 
    background: transparent;
    border: 2px solid black;
    height: 240px;
}

.test1 {
    border: 2px solid green;
    width: 200px;
    height: 30px;
    position: relative;
    right: 0;
}

.test2 {
    border: 2px solid red;
    width: 600px;
    height: 200px;
    position: relative;
}

.test3 {
    border: 2px solid black;
    width: 100px;
    height: 20px;
    position: absolute;
    bottom: 20px;
    right: 0;
}

Note:

  1. position: relative can do the same stuff as position: absolute, AND things still flow as if the element was still in its default position (but it doesn't have to be).
  2. position: absolute takes that element out of the flow
  3. position: fixed is the same as absolute but with reference to the window itself (think fixed navigation bars)

Post a Comment for "How Do I Stack Div Elements On Top Of Each Other With Position: Relative"