为什么我的内联块 div 中只有一个有文本时没有对齐? [英] Why my inline-block divs are not aligned when only one of them has text?
问题描述
实时页面
<块引用>基线
<块引用>将框的基线与父框的基线对齐.如果盒子没有基线,将底部边距边缘与父级基线对齐.(我的重点)
因为内联块的默认对齐方式是基线",除非它被覆盖,否则此规则适用.当文本放入行内块时,该文本将为行内块创建基线,并且第一个(非粗体)句子适用.
当 inline-block 中没有文本时,它就没有基线,因此第二个(粗体)句子适用.
在这里的 JSFiddle:http://jsfiddle.net/WjCb9/1/ 我有从你的例子中删除了 margin:1em
,它创造了(至少对我来说)一个误导性的错觉,并添加了文本 baseline
以显示包含框的基线在哪里.基线沿着单词基线"的底部,因此您可以看到空行内块的底部边距边缘与上面 CSS 规则要求的父级基线对齐.
Live page here.
Given this HTML page:
section[role=main] {
margin: 1em;
width: 95%;
border: 1px solid #999;
}
section[role=main] article {
width: 40%;
height: 180px;
margin: 1em;
display: inline-block;
border: 1px solid black;
}
<section role="main">
<article>Java</article>
<article></article>
</section>
<section role="main">
<article>Java</article>
<article>JavaScript</article>
</section>
I expect both of my articles to be aligned, but as it can be seen in the screenshot below, only when both of my articles have text the <article>
elements are center aligned:
Any ideas what is causing this behavior and how can it be fixed?
This is the consequence of the "baseline" vertical alignment in CSS. From the CSS 2.1 spec, section 10.8 Line height calculations: the 'line-height' and 'vertical-align' properties
baseline
Align the baseline of the box with the baseline of the parent box. If the box does not have a baseline, align the bottom margin edge with the parent's baseline. (my emphasis)
Because the default alignment for the inline-blocks is "baseline", unless it is overridden, this rule applies. When text is put in the inline-block, that text will create a baseline for the inline-block and the first (non-bolded) sentence applies.
When there is no text in the inline-block, then it has no baseline and so the second (bolded) sentence applies.
In the JSFiddle here: http://jsfiddle.net/WjCb9/1/ I have removed from your example the margin:1em
which was creating (at least for me) a misleading illusion, and added the text baseline
to show where the baseline of the containing box is. The baseline is along the bottom of the word "baseline", so you can see that the empty inline-block has its bottom margin edge aligned with the parent's baseline as required by the CSS rule above.
这篇关于为什么我的内联块 div 中只有一个有文本时没有对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!