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

发布于 2024-08-31 23:18:21 字数 1359 浏览 2 评论 0原文

考虑以下内容:

<!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>

这呈现为:

框 2 低于框 1 http://img.skitch .com/20100512-cr58jx4p5k37n4fcm6cn8h6dde.png

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

Consider the following:

<!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>

This is rendered as:

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

Why is box 2 not at the same level than box 1? It has a position: absolute, no top or left, and so I would expect it to be taken out of the normal flow with no impact to its position. (Note that I am not trying to fix a "problem" by changing the CSS, but to understand why browsers render this box this way.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

久伴你 2024-09-07 23:18:21

这是因为 td 有一个原生的 vertical-align:middle。由于您的 .box-2 不再占用任何空间,因此顶部设置为单元格的中间。如果将 tdvalignvertical-align 设置为 top,它将按照您期望的方式工作。

It's because td have a native vertical-align:middle. Because your .box-2 no longer occupies any space, the top is set to the middle of the cell. If you set the valign or vertical-align of td to top, it will work the way you expect.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文