Allison
Allison

Reputation: 89

I cant get a div to sit 20 px below another div that has a varying height

I know this is probably very simple but I have tried using all position settings, float, and nesting. The top div varies in height due to dynamically created text and I need the div below it to be 20px below the top div. Any help is greatly appreciated. I know I have the position as absolute but that is just to demonstrate kind of what I'm looking for.

#wrapper {
    position:absolute;
    width:341px;
    height:371px;
    z-index:1;
    border: solid #777 1px;
}
#topbox {
    position:absolute;
    width:280px;
    z-index:1;
    padding: 30px;
    border: solid #000 1px;
    top: 7px;
}
#bottombox {
    position:absolute;
    width:280px;
    z-index:1;
    padding: 30px;
    top: 136px;
    border: solid #000 1px;
}
<div id="wrapper">
  <div id="topbox">Top text  box #1. The text is dynamically created  here with a height that will vary. </div>
  <div id="bottombox">Bottom text box #2. The text is dynamically created here with a height that will vary and needs to be 20px below the bottom of the top text box.</div>
</div>

Upvotes: 1

Views: 215

Answers (2)

Giacomo1968
Giacomo1968

Reputation: 26084

Looking at the CSS you have, the problem is you are using absolute positioning. For a task like this you should use relative positioning. Here it is on jsFiddle to show you it in action & here is the CSS I adjusted to achieve that:

#wrapper
{
    position: relative;
    float: left;
    display: inline;
    width: 341px;
    min-height: 371px;
    z-index: 1;
    border: solid #777 1px;
}

#topbox
{
    position: relative;
    float: left;
    display: inline;
    width: 280px;
    z-index: 1;
    padding: 30px;
    margin: 7px 0 0 0;
    border: solid #000 1px;
}

#bottombox
{
    position: relative;
    float: left;
    display: inline;
    width: 280px;
    z-index: 1;
    padding: 30px;
    margin: 20px 0 0 0;
    border: solid #000 1px;
}

Here is how it renders in my local browser now:

enter image description here

I also looked over your CSS & combined/consolidated it since I find that repeating code can cause confusion when debugging items like this. Here is how I would code this:

#wrapper, #topbox, #bottombox
{
    position: relative;
    float: left;
    display: inline;
}

#topbox, #bottombox
{
    width: 280px;
    z-index: 1;
    padding: 30px;
    border: solid #000 1px;
}

#wrapper
{
    width: 341px;
    min-height: 371px;
    z-index: 1;
    border: solid #777 1px;
}

#topbox { margin: 7px 0 0 0; }
#bottombox { margin: 20px 0 0 0; }

Upvotes: 3

meadowstream
meadowstream

Reputation: 4151

To give #topBox a bottom margin you simply have to use:

#topBox {
  margin-bottom: 20px;
}

The problem is that since you use position: absolute the elements jumps out of their normal flow and will no longer relate to each other.

Upvotes: 1

Related Questions