Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position relative DIVS

Tags:

css

position

I always see code like this:

#container {
    background:#000000 none repeat scroll 0 0;
    display:block;
    overflow:hidden;
    position:relative;
    width:100%;
}

I thought position relative is used to accommodate the div relatively to its parent element using the CSS proprieties left right top and bottom (px). What's the point of using it alone like the example below? Which other properties are being affected by position relative?


1 Answers

Child elements position can get affected by this.

After setting parent elements position to relative, when we try to set the child elements position to be absolute then it will be absolutely placed relative to the parent only and not to the document.

First example

<style>
    #container 
    {
        background:red none repeat scroll 0 0;
        display:block;
        position:relative;
        top: 100px; 
        left: 100px;
        width:100%;
    }
    #child
    {
        position: absolute; 
        top: 0px;
        left: 0px;
    }

</style>
<div id="container">
    <div id="child">
        I am absolutely placed relative to the container and not to the document
    </div>
</div>

Second Example

<style>
    #container 
    {
        background:red none repeat scroll 0 0;
        display:block;
        top: 100px; 
        left: 100px;
        width:100%;
    }
    #child
    {
        position: absolute; 
        top: 0px;
        left: 0px;
    }

</style>
<div id="container">
    <div id="child">
        I am absolutely placed relative to the container and not to the document
    </div>
</div>

Try to check the above two examples and you will see the difference.

like image 59
Ouadi Avatar answered Aug 02 '26 01:08

Ouadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!