【问题标题】:How is the css property top calculated for absolute elements that do not set the property themselves? [duplicate]自己不设置属性的绝对元素的css属性top是如何计算的? [复制]
【发布时间】:2012-07-26 15:15:11
【问题描述】:

可能重复:
position: absolute without setting top/left/bottom/right?

看下面的代码,我有 div#box2 有 position: absolute 设置就可以了。它位于两个具有 position: static 设置的 div 之间。根据以下代码,我希望 div#box2 位于 body 元素的左上角。但是,当它被渲染时,它会收到一个将其置于 box1 下方的最高值。为什么会这样?

我了解当我将 div#box2 的顶部值显式设置为 0px 时,它会出现在顶部。我只是不知道为什么浏览器一开始就没有计算到 0px 。

这里是一些示例代码:

<!DOCTYPE html>
<html>
  <head>
    <title>Position Test</title>
    <style type="text/css">
      body { background-color: #DEDEDE; }
      #content { border: solid; }
      #content div { height: 150px; opacity: .7;}
      #box1 { background-color: red; }
      #box2 { background-color: yellow; }
      #box3 { background-color: lightblue; }

    #content div { width: 150px; }
        #box2 { position: absolute; text-align: right;}
    </style>
  </head>
  <body>
    <div id="content">
      <div id="box1"><span>1</span></div>
      <div id="box2"><span>2</span></div>
      <div id="box3"><span>3</span></div>
    </div>
  </body>
</html>

【问题讨论】:

  • 你想把 div box 2 放在 div box 1 的位置吗?
  • 为什么没有设置为'position:relative'的div?

标签: html css


【解决方案1】:

top默认值是“auto”,而不是“0”(source),因此它不应位于顶部&lt;body&gt; 元素。

至于为什么“auto”转换为“与positionstatic 相同的位置”,请参阅CSS specification on positioning(强调我的):

对于绝对定位的元素,垂直尺寸的使用值必须满足这个约束:

'top' + 'margin-top' + 'border-top-width' + 'padding-top' + 'height' + 'padding-bottom' + 'border-bottom-width' + 'margin-bottom' + 'bottom' = 包含块的高度

如果 'top'、'height' 和 'bottom' 三个都是 'auto':首先将 'margin-top' 和 'margin-bottom' 的任何 'auto' 值设置为 '0' ,然后将'top'设置为静态位置,最后应用下面的规则三。

...

【讨论】:

  • 所以使用top: 0px; left 0px; ..nice 1 mate..
  • 我知道top的默认值是auto。我只是很困惑为什么计算的自动值将 div#box2 放在 div#box1 之下。阅读MDN,它表示绝对定位元素相对于其最近的定位祖先进行定位。我假设这意味着绝对定位的元素会自动计算 0 的最大值,因为它是相对于最近的定位元素。你的答案是正确的,但我会选择@Jrod,因为他解释了如何计算最高值。
【解决方案2】:

当一个元素被赋予绝对位置时,它被从流中取出,允许其他元素放置在它的上方或下方。如果没有明确设置顶部值,顶部值将保留元素位置,如果它没有从流中删除。

如果我们切换框的顺序,您会看到发生这种情况,因为 #box2 已完全从流程中删除,位于 #content 之外,但仍会堆叠在具有 position:static 时的位置

<!DOCTYPE html>
<html>
  <head>
    <title>Position Test</title>
    <style type="text/css">
      body { background-color: #DEDEDE; }
      #content { border: solid; }
      #content div { height: 150px; opacity: .7;}
      #box1 { background-color: red; }
      #box2 { background-color: yellow; }
      #box3 { background-color: lightblue; }

    #content div { width: 150px; }
        #box2 { position: absolute; text-align: right;}
    </style>
  </head>
  <body>
    <div id="content">
      <div id="box1"><span>1</span></div>
      <div id="box3"><span>3</span></div>
      <div id="box2"><span>2</span></div>

    </div>
  </body>
</html>

【讨论】:

  • 您是否有任何文档/文章/任何解释“如果没有明确设置最高值,如果没有从流程中删除最高值将保留元素位置?”谢谢!
猜你喜欢
  • 2019-07-08
  • 1970-01-01
  • 2017-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-03
  • 2014-02-23
  • 2011-02-14
相关资源
最近更新 更多