图像与 css 垂直对齐 - 奇怪
我有以下代码:
<html>
<head>
<style type="text/css">
#test img {vertical-align: middle;}
div#test {
border: 1px solid green;
height: 150px;
line-height: 150px;
text-align: center;
color: white
}
</style>
</head>
<body>
<div id="test">t<img class="bottom" src="http://www.w3schools.com/css/w3schools_logo.gif" alt="W3Schools" width="270" height="50" /></div>
</body>
</html>
如果我删除图像后面的 t ,那么它不会在中心垂直对齐(我在 Firefox 中测试它)。因为它现在是对齐的,所以我可以将文本的颜色更改为与背景相同,或者另一种方法是放置内联样式并将其设置为背景。
还有其他方法可以用 CSS 垂直对齐图像吗?我发现这些方法有点hack。 这在 CSS3 中如何运作?
I have the following code:
<html>
<head>
<style type="text/css">
#test img {vertical-align: middle;}
div#test {
border: 1px solid green;
height: 150px;
line-height: 150px;
text-align: center;
color: white
}
</style>
</head>
<body>
<div id="test">t<img class="bottom" src="http://www.w3schools.com/css/w3schools_logo.gif" alt="W3Schools" width="270" height="50" /></div>
</body>
</html>
If I remove the t after the the image, then it doesn't align vertically in the center (I test it in firefox). As it is now it aligns, so I could change the color of the text to be the same as the background or the other way was to put an inline style and set it as a background.
Is there any other way to align vertically an image with CSS? I found these ways to be a bit of a hack.
How would that worked in CSS3?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
t
产生差异的原因是,如果图像是唯一的元素,或者它们是文本的一部分,则图像的处理方式会有所不同。如何将图像视为单个元素取决于页面的渲染模式。在开始时,图像作为单个元素被视为块元素,并且在某些情况下保留该行为以向后兼容。您应该放置 正确的文档在页面上输入,这样它就不会被渲染在怪异模式下,如果它不能解决您的问题,至少它会使其行为更加一致。
The reason that the
t
makes a diffence, is because images are treated differently if they are the only element, or if they are part of a text.How images are treated as single elements depend on the rendering mode of the page. In the beginning images as single elements were treated as block elements, and that behaviour is retained in certain sitations to be backwards compatible. You should put a proper doctype on the page, so that it's not rendered in quirks mode, if it doesn't solve your problem, at least it will make it behave more consistently.
使用
代替 t 字符,它是一个空格。
但我不知道为什么会发生这种情况。大家有什么建议吗?
instead of t character use
it is an space.
but i dont know why this happen. any suggestion guys?
我认为您的问题是将
vertical-align
属性应用于错误的元素 - 它应该应用于 img 的周围元素,即您的情况下的div#test
:我不知道为什么它会添加
t
符号,也许是浏览器的怪癖?I think your problem is applying the
vertical-align
property on a wrong element - it should be applied to the surrounding element of the img, that isdiv#test
in your case:I don't know why it works with the
t
symbol added, perhaps a browser quirk?