views:

63

answers:

5

Hi,

I'm trying to place a div with id 'absPos' in absolute position in relation to its parent div. But it is not working, the div is placed at the top left corner of the page.

My code sample is as follows

<html>
    <body>
        <div style="padding-left: 50px;">
            <div style="height: 100px">
                Some contents
            <div>

            <div style="height: 80px; padding-left: 20px;">
                <div id="absPos" style="padding: 10px; position: absolute; left: 0px; top: 0px; background-color: red;"></div>
                Some text
            </div>
        </div>
    </body>
</html>

Can you help me to solve this issue. In my actual case instead of the red background color I've to place a background image.

Regards

+7  A: 

Apply position:relative to the parent div.

<html>
    <body>
        <div style="padding-left: 50px;">
            <div style="height: 100px">
                Some contents
            <div>

            <div style="height: 80px; padding-left: 20px; position: relative;">
                <div id="absPos" style="padding: 10px; position: absolute; left: 0px; top: 0px; background-color: red;"></div>
                Some text
            </div>
        </div>
    </body>
</html>
Andy E
+2  A: 

You need to give parent div relative position first:

<div style="height: 80px; padding-left: 20px; position:relative;">
Sarfraz
+2  A: 

You need to declare the parent div either position: relative or position: absolute itself.

relative is what you're looking for in this case.

Pekka
+2  A: 

If you are placing an element with absolute position, you need the base element to have a position value other than the default value.

In your case if you change the position value of the parent div to 'relative' you can fix the issue.

Santhosh
+1  A: 

You can also Apply Position:absolute to the Parent Div. Total Code below

<html>
    <body>
        <div style="padding-left: 50px;">
            <div style="height: 100px">
                Some contents
            <div>

            <div style="height: 80px;position:absolute; padding-left: 20px;">
                <div id="absPos" style="padding: 10px; position: absolute; left: 0px; top: 0px; background-color: red;"></div>
                Some text
            </div>
        </div>
    </body>
</html>
Rajasekar