Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Div position:relative alignment problem

Tags:

html

css

I have a problem about div position relative alignment.

I want the second div to be fixed in position even if I remove the first div. The problem is that the second div adjusts its position when the first div is removed.

My question is how can I retain the position of the second div even if I remove the first div? Thanks :)

This code:

<div style="border: 1px solid red;width:400px;height:150px;margin:0px auto;" >

    <div style="border: 1px solid red; position: relative;
    width: 262px; height: 20px; top: 20px; left: 20px;">div-1</div> 

    <div style="border: 1px solid red; position: relative;
    width: 262px; height: 20px; top: 60px; left: 20px;">div-2</div>
</div>

Will output:

alt text

Then if the first div is removed, the second div adjusts its position. This code:

<div style="border: 1px solid red;width:400px;height:150px;margin:0px auto;" >

    <div style="border: 1px solid red; position: relative;
    width: 262px; height: 20px; top: 60px; left: 20px;">div-2</div>
</div>

Will output: alt text

like image 296
marknt15 Avatar asked Dec 17 '22 08:12

marknt15


2 Answers

If you set the positioning of the outer element to relative, then absolute positioned elements inside of it will be positioned relative to the enclosing one:

<div style="border: 1px solid red;width:400px;height:150px;margin:0px auto; position:relative" >
    <div style="border: 1px solid red; position: absolute;
    width: 262px; height: 20px; top: 20px; left: 20px;">div-1</div>
    <div style="border: 1px solid red; position: absolute;
    width: 262px; height: 20px; top: 60px; left: 20px;">div-2</div>
</div>

Now you can remove div1 and div2 won't move.

like image 163
Jordi Avatar answered Jan 26 '23 00:01

Jordi


use absolute positioning, which will make the inner div's position absolute to the parent div (aka containing block).

And I would recommend not using inline styles and use a stylesheet:

<style type="text/css">
    #top 
    {
        position:relative;
        border: 1px solid red;
        width:400px;
        height:150px;
        margin:0px auto;
    }

    #child1, #child2
    {
        position: absolute;
        border: 1px solid red;
        width: 262px;
        height: 20px;
        left: 20px;
    }

    #child1 
    { top: 20px; }
    #child2
    { top: 60px; }
</style>    

 <div id="top">
    <div id="child1">div-1</div>
    <div id="child2">div-2</div>
</div>

http://kilianvalkhof.com/2008/css-xhtml/understanding-css-positioning-part-1/

like image 24
Chad Grant Avatar answered Jan 25 '23 23:01

Chad Grant