CSS:Div位置:相对对齐问题

mar*_*t15 4 html css

我有关于div位置相对对齐的问题.

即使我删除第一个div,我希望第二个div固定在位.问题是第二个div在第一个div被移除时调整其位置.

我的问题是,即使我删除第一个div,我如何保留第二个div的位置?谢谢 :)

这段代码:

<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>
Run Code Online (Sandbox Code Playgroud)

将输出:

替代文字

然后,如果删除第一个div,则第二个div调整其位置.这段代码:

<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>
Run Code Online (Sandbox Code Playgroud)

将输出: 替代文字

Jor*_*rdi 11

如果将外部元素的定位设置为relative,则其中的绝对定位元素将相对于封闭的元素定位:

<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>
Run Code Online (Sandbox Code Playgroud)

现在你可以删除div1并且div2不会移动.