以下是我的代码,我想了解为什么#firstDiv被所有浏览器向下推。我真的很想了解它的内部工作原理为什么它被向下推,而不是以某种方式向上拉。(而且我知道如何对齐它们的顶部:))

我知道它的溢出是隐藏的;这导致了它,但不确定为什么它把div往下推。

body { width: 350px; margin: 0px auto; } #container { border: 15px solid orange; } #firstDiv { border: 10px solid brown; display: inline-block; width: 70px; overflow: hidden; } #secondDiv { border: 10px solid skyblue; float: left; width: 70px; } #thirdDiv { display: inline-block; border: 5px solid yellowgreen; } <div id="container"> <div id="firstDiv">FIRST</div> <div id="secondDiv">SECOND</div> <div id="thirdDiv">THIRD <br>some more content<br> some more content </div> </div>

http://jsfiddle.net/WGCyu/。


当前回答

CSS中垂直对齐的默认值是baseline &此规则也适用于内联块读取此http://www.brunildo.org/test/inline-block.html

在你的内联块DIV中写入vertical-align:top。

检查这个http://jsfiddle.net/WGCyu/1/

其他回答

CSS中垂直对齐的默认值是baseline &此规则也适用于内联块读取此http://www.brunildo.org/test/inline-block.html

在你的内联块DIV中写入vertical-align:top。

检查这个http://jsfiddle.net/WGCyu/1/

只需使用vertical-align:top;

Demo

尝试添加填充:0;对身体和删除边缘的divs。

添加background-color:*除background*以外的任何颜色来检查差异。

这个问题是因为你在第二个div上应用了float:left,这使得第二个div在左边,第一个div落在第二个div之后。 如果你在第一个div上也使用float:left,你的问题就会消失。

溢出:隐藏不会对你的布局造成任何问题,溢出:隐藏只影响一个div的内部元素,它与外部的其他元素无关。

我最初开始回答这个问题,但在我完成之前它被锁定为欺骗,所以我把答案贴在这里。

首先,我们需要理解什么是内联块。 MDN中的定义是这样的:

元素生成一个块元素框,将与之一起流动 围绕内容,就好像它是一个内联框(行为 就像替换的元素一样)

为了理解这里发生了什么,我们需要看看vertical-align,它的默认值baseline。

在这个插图中,你有这个颜色表: 蓝色:基线 红色:行高的顶部和底部 绿色:内嵌内容框的顶部和底部。

在#left元素中,确实有一些文本内容控制基线是什么。这意味着里面的文本定义了#left的基线。 在#右侧,没有内容,所以浏览器只能使用框底部作为基线。

Se这个可视化的地方,我已经在一个例子中绘制了基线,其中第一个内联容器有一些文本,下一个是空的:

如果你特别地将一个元素对齐到顶部,你实际上是在将这个元素的顶部对齐到行框的顶部。

举个例子可能更容易理解。

div { 显示:inline-block; 宽度:100 px; 身高:150 px; 背景:灰色; vertical-align:基线; } div #{中间 vertical-align:最高; 高度:50 px } 正确div # { 字体大小:30 px; 身高:100像素 } < div id = "左" > groovy < span > < / span > < / div > groovy < div id = "中间" > < / div > groovy < div id = "正确" > < / div >

The result is this - and I added the blue baseline, and the red line box: What happens here, is that the height of line box is depended on how the the content of the entire line is laid out. This means that to calculate the top alignment, the basline alignments must be calculated first. The #middle element has vertical-align:top, so this is not used for the baseline positioning. but the #left and #right are positioned vertically so that their baselines are aligned. When this is done, the height of the line box has increased, because the #right element has been pushed up a bit as a result of the larger font size. Then the top position for the #middle element can be calculated, and this is along the top of the line box.