html - 对于本身不设置属性的绝对元素,css 属性 top 是如何计算的?

标签 html css

<分区>

Possible Duplicate:
position: absolute without setting top/left/bottom/right?

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

我理解当我将div#box2 的top 值明确设置为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>

最佳答案

top默认 值是“auto ”,而不是“0” ( source ),因此它不应位于 <body> 的顶部元素。

至于为什么“auto”翻译成“与positionstatic 的位置相同”,参见CSS specification on positioning (强调我的):

For absolutely positioned elements, the used values of the vertical dimensions must satisfy this constraint:

'top' + 'margin-top' + 'border-top-width' + 'padding-top' + 'height' + 'padding-bottom' + 'border-bottom-width' + 'margin-bottom' + 'bottom' = height of containing block

If all three of ‘top’, ‘height’, and ‘bottom’ are ‘auto’: First set any ‘auto’ values for ‘margin-top’ and ‘margin-bottom’ to ‘0’, then set ‘top’ to the static position, and finally apply rule number three below.

...

关于html - 对于本身不设置属性的绝对元素,css 属性 top 是如何计算的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11672490/

相关文章:

css - Visual Studios CSS 支持有什么值(value)?

css - svg 文件中星星的旋转动画

css - 保持容器的内联行为,但将其高度设置为所需值

css - 添加水平滚动阴影效果

html - 将 Apache Mod Rewrite 规则转换为 NGINX

javascript - 在使用 XMLHttpRequest 调用的 DIV 上执行 JQuery 函数?

javascript - 在 iframe 中玩游戏时禁用滚动父页面

javascript - Stylus:生成 CamelCase 变量

javascript - 将整个 HTML 页面存储到 jQuery 变量中

jquery - 有没有办法在使用 jQuery 数据表插件的 HTML 表中获取当前记录数