为什么这两个相同的内联div在一个有文本时不对齐,而另一个没有? [英] Why are these two identical inline divs misaligned when one has text and the other doesn't?

查看:130
本文介绍了为什么这两个相同的内联div在一个有文本时不对齐,而另一个没有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有两个相同的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.

jsFiddle example

这篇关于为什么这两个相同的内联div在一个有文本时不对齐,而另一个没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆