【问题标题】:How does the CSS position on a div affects position of sibling division?div 上的 CSS 位置如何影响同级划分的位置?
【发布时间】:2013-02-12 08:20:06
【问题描述】:

我一直在经历CSS Positions articles on Alistapart。下面的 sn-p 引起了我的注意,无法理解背后的理论。

下面的 html/css 显示两个框并排。但是如果我将#box_1 的位置改为绝对位置,那么#box_2 会与#box_1 重叠。

<!DOCTYPE html >
<html lang="en">
<head>
    <style>
        #box_1 { 
            position: relative;
            width: 200px;
            height: 200px;
            background: #ee3e64;
        }
        #box_2 { 
            position: absolute;
            width: 200px;
            height: 200px;
            background: #44accf;
        }
    </style>
</head>
<body>
    <div id="box_1"></div>
    <div id="box_2"></div>
</body>
</html>
  1. 另一个框 (box_1) 的位置如何影响不同/兄弟 div(box_2) 的位置。 'absolute' 不应该永远只对直接的非静态父级是绝对的吗?

  2. 在上面的 css 中(在 box_1 中带有“position: relative;”),如果我添加“top: 0;”到 #box_2,然后 box_2 似乎再次重叠。为什么会这样?

【问题讨论】:

    标签: html css


    【解决方案1】:

    如果您不指定其toprightbottomleft 属性中的任何,则绝对定位元素将保持在其静态位置,无论是否它的任何祖先都已定位。这就是为什么当您简单地将其设置为 position: absolute 时,#box_2 似乎没有发生任何事情 - 相反,它会受到 #box_1 的影响,就像您没有指定 position: absolute 一样。

    但是,请注意#box_1 影响#box_2 只是因为 1 在 2 之前;一旦您绝对定位#box_2,它就会从流程中取出,并且任何跟随它的兄弟姐妹都会像#box_2 不再存在一样流动。请参阅this example,其中我创建了一个与#box_1 相同的#box_3 并将其添加 #box_2,其中#box_3#box_2 重叠,因为3 在正常流量;它只看到 1。

    一旦您将top: 0 设置为#box_2,它就会知道它必须附加到视口的顶部(作为它的包含块,因为它的祖先都没有被定位)。

    【讨论】:

    • 啊,这就是我要找的东西(“如果你不指定它的任何顶部、右侧、底部或左侧属性,绝对定位的元素将保持在其静态位置”)。非常感谢,+10 票;如果只有 sf 允许的话:)
    • 很高兴知道,但有没有解决方案可以正常显示#box_3,而#box_2 绝对定位! @BoltClock
    【解决方案2】:

    div 上的 CSS 位置不影响兄弟分割的位置,但会影响子元素。例如:

    HTML:

      <div id="parent_1">
         <div id="child_1"></div>
         <div id="child_2"></div>
      </div>
    

    CSS:

      #parent_1{ 
            position: relative;
            width: 400px;
            height: 400px;
            background: gray;
        }
     #child_1 {
        position: absolute;
        left:20px;
        top:20px;
        width:40px; 
        background:yellow;
     }
    #child_2 {
        position: absolute;
        right:20px;
        top:20px;
        width:40px; 
        background:blue;
     }
    

    现在 #parent_1 将创建一个 400*400 的框,并且 #child_1 将放置在父 div 内,并将位于距左侧 20px 和距顶部 20px 的位置。

    【讨论】:

    • 这与问题有什么关系/答案?
    • 您的问题是“div 上的 CSS 位置会影响同级分区的位置?”,我的回答是否定的,它不会,它只影响子分区/子元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    相关资源
    最近更新 更多