为什么这两个相同的内联div在一个有文本时不对齐,而另一个没有? [英] Why are these two identical inline divs misaligned when one has text and the other doesn't?
问题描述
这里有两个相同的div:
HTML
< div id =left>< / div>
< div id =right>< / div>
CSS
#left,#right
{
width:100px;
height:40px;
border:1px solid gray;
display:inline-block;
}
这些渲染很好,两个相同的盒子并排:)
This ...
< div id =left> / div>
< div id =right>右< / div>
...结果:
此行为可使用< span>
。
这是什么原因,为什么?
简短回答:设置 vertical-align
属性到顶部
。 / strong>:内联元素的
So here are two identical divs:
HTML
<div id="left"></div>
<div id="right"></div>
CSS
#left, #right
{
width: 100px;
height: 40px;
border: 1px solid gray;
display: inline-block;
}
These render just fine, as two identical boxes side-by-side (fiddle: http://jsfiddle.net/URy59/).
But with text in one div, and none in the other, they're misaligned! (fiddle: http://jsfiddle.net/URy59/1/)
This...
<div id="left"></div>
<div id="right">Right</div>
...results in:
This behaviour is reproducible using <span>
as well.
What causes this, and why? What's a good solution to this?
The short answer: set the vertical-align
property to top
.
The longer answer: An inline element's default vertical alignment is baseline. When your divs have no content, they line up fine. However when you added the text, the browser then will move the div downward so that the text sits on the baseline:
By changing the alignment to top, you align the divs the way you need.
这篇关于为什么这两个相同的内联div在一个有文本时不对齐,而另一个没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!