Why does an inline-block align to top if it has no content?

╄→гoц情女王★ 提交于 2019-12-19 04:22:53

问题


I have the following simple setup:

HTML

<input type=text>
<a></a>
<a>text</a>
<span></span>
<span>text</span>

CSS

input {
    width: 50px;
    height: 25px;
}

span, a {
    display:inline-block;
    width: 50px;
    height: 25px;
    background: green;
    color: white;
}

span {
       background: blue;
}

You can see that first anchor element and first span element is aligned to the top, while second anchor and span align on the same baseline as the input. Why so?


回答1:


The baseline of an inline-block that has no inline children, including text, is its bottom margin edge (or simply bottom edge if it has no bottom margin). This baseline is then aligned with the baselines of the rest of the text. This is mentioned at the very end of section 10 of the spec.




回答2:


Nothing is vertically top aligned, only content is missing. If you use <a>&nbsp;</a>everything would be fine - look here. An empty inline tag has no baseline, so its bottom edge was used for alignment.

You have several solutions to align empty inline block tags:

  • add &nbsp; (and they won't be empty anymore)
  • as BoltClock suggested, add an invisible character in :before
  • change to vertical-align: bottom


来源:https://stackoverflow.com/questions/27293843/why-does-an-inline-block-align-to-top-if-it-has-no-content

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!