CSS:位置为绝对的框,顶部/左侧没有偏移
考虑以下内容:
<!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
,没有 top
或 left
,所以我希望它能从正常流程中取出而不会产生任何影响到它的位置。 (请注意,我并不是试图通过更改 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为
td
有一个原生的vertical-align:middle
。由于您的.box-2
不再占用任何空间,因此顶部设置为单元格的中间。如果将td
的valign
或vertical-align
设置为top
,它将按照您期望的方式工作。It's because
td
have a nativevertical-align:middle
. Because your.box-2
no longer occupies any space, the top is set to the middle of the cell. If you set thevalign
orvertical-align
oftd
totop
, it will work the way you expect.