iRebel_85
iRebel_85

Reputation: 749

CSS Position Absolute NOT ignoring element with no positioning

I have a <div> with a few <h1>,<h2>,and <p> tags inside, then I have a <div> below these h1,h2,and p tags inside of this parent <div>. I have position: relative; on the parent <div> and position:absolute; top:0px; on the child <div>. There is no positioning set in the css for the h1,h2, and p tags. The result I'm getting is, the child <div> is positioning to the bottom of the other child elements and not positioning to the very top of the parent div. Is this what is supposed to be happening?

** HTML **

<div id="parentDiv">
   <h1>Header</h1>
   <h2>sub header</h2>
   <p>paragraph text</p>
   <div id="displayAtTop">test</div>
</div>

** CSS **

#parentDiv {
   position: relative;
   width: 500px;
   min-height: 300px;
}

#parentDiv h1, #parentDiv h2, #parentDiv p {
   margin-left: 30px;
   margin-top: 30px;
}

#displayAtTop {
   position: absolute;
   top: 0px;
   left: 350px;
}

I thought absolute positioning was supposed to ignore everything and place it at the very top of the closest parent element with positioning set.

Upvotes: 1

Views: 1512

Answers (1)

John Haugeland
John Haugeland

Reputation: 9668

The code works as expected.

I added a red border to make it easier to see.

I think you might be mistaking the <body> or <html> padding/margin for a problem.

  <head>
    <style type="text/css">

        #parentDiv {
           position: relative;
           width: 500px;
           min-height: 300px;
           border: 1px solid red;
        }

        #parentDiv h1, #parentDiv h2, #parentDiv p {
           margin-left: 30px;
           margin-top: 30px;
        }

        #displayAtTop {
           position: absolute;
           top: 0px;
           left: 350px;
        }

    </style>
  </head>

  <body>

    <div id="parentDiv">
       <h1>Header</h1>
       <h2>sub header</h2>
       <p>paragraph text</p>
       <div id="displayAtTop">test</div>
    </div>

  </body>
</html>

http://jsfiddle.net/StoneCypher/Lq95hcqe/

Upvotes: 2

Related Questions