CSS: Div position: relative alignment problem

I have a problem with relative alignment of the position of the div.

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

My question is how to keep the position of the second div even if I delete 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> 

It will display:

alt text

Then, if the first div is deleted, the second div will change 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> 

It will display: alt text

+4
source share
4 answers

If you set the positioning of the external element relative to, then the absolute positioned elements inside it will be located relative to the surrounding:

 <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 will not move.

+11
source

use absolute positioning that will make the inner position of the div absolute for the parent div (aka contains block).

And I would recommend not using inline styles and using 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/

+1
source

You can use absolute positioning - position: absolute or display: none (css).

0
source

You can set the CSS visibility property on DIV1 to hidden, and even being invisible, it will take its original space on the page.

 <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; visibility:hidden;">div-1</div> <div style="border: 1px solid red; position: relative; width: 262px; height: 20px; top: 60px; left: 20px;">div-2</div> </div> 
0
source

All Articles