问题
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> </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
(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