CSS:具有位置的框:绝对,没有顶部/左边有偏移

时间:2010-05-12 18:58:02

标签: css position css-position

请考虑以下事项:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <style type="text/css">
            .box-2 { position: absolute }

            /* Styling */
            .box-1 { background-color: #ccc; width: 3em  }
            .box-2 { background-color: #ddd; width: 3em  }
        </style>
    </head>
    <body>
        <table>
            <tr>
                <td>
                    <div class="box-1">1</div>
                </td>
                <td>
                    <div class="box-2">2</div>
                </td>
            </tr>
        </table>
    </body>
</html>

这表现为:

Box 2 lower than box 1 http://img.skitch.com/20100512-cr58jx4p5k37n4fcm6cn8h6dde.png

为什么方框2与方框1不在同一水平?它有一个position: absolute,没有topleft,所以我希望它可以从正常流程中取出而不影响其位置。 (请注意,我不是试图通过更改CSS来修复“问题”,而是要了解浏览器为何以这种方式呈现此框。)

1 个答案:

答案 0 :(得分:2)

这是因为td有一个原生的vertical-align:middle。因为.box-2不再占用任何空间,所以顶部设置在单元格的中间。如果您将valign的{​​{1}}或vertical-align设置为td,它将按预期方式运行。

相关问题