为什么我的inline-block div只有一个文本没有对齐? [英] Why my inline-block divs are not aligned when only one of them has text?

查看:114
本文介绍了为什么我的inline-block div只有一个文本没有对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


实时页面


baseline




将框的基线与父框的基线对齐。 如果方框
没有基线,请将底边距边缘与父项的基线对齐。
(我强调)



由于inline-blocks的默认对齐方式是baseline,除非被覆盖,否则此规则适用。当文本放在inline-block中时,该文本将为inline-block创建一个基线,并应用第一个(非粗体)句子。



当inline-block中没有文本时,它没有基线,因此第二个(粗体)句子适用。



在JSFiddle中: http://jsfiddle.net/WjCb9/1/ 我已从你的例子是 margin:1em ,它创造了一个误导性的错觉,并添加了 baseline 以显示包含框的基线的位置。基线沿着baseline的底部,因此您可以看到空的inline-block的底边距边缘与上述CSS规则所要求的父级基线对齐。


Live page here.

Given this HTML page:

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>        
    </head>

    <body>
        <section role="main"><article>
                Java
            </article><article>

        </article></section>

      <section role="main"><article>
                Java
            </article><article>
JavaScript
        </article></section>
    </body>
</html>

When I apply the following CSS:

section[role=main] {
  margin: 1em;
  width: 800px;
  border: 1px solid #999;
}

section[role=main] article {
  width: 320px;
  height: 180px;
  margin: 1em;
  display: inline-block;
  border: 1px solid black;
}

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.

这篇关于为什么我的inline-block div只有一个文本没有对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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