在 CSS 中使用 float 时,为什么垂直对齐不能正常工作?

如何在 div属性中使用 vertical-alignfloat?如果我不使用 floatvertical-align工作得很好。但如果我使用浮动,那么它不工作。使用 float:right作为最后一个 div 对我来说很重要。

我正在尝试跟随,如果你从所有的 div 中删除浮动,那么它将工作正常:

<div class="wrap">
<div class="left">First div, float left,  has more text.</div>
<div class="left2">Second div, float left </div>
<div class="right">Third div, float right</div>
</div>

CSS:

.wrap{
width: 500px;
overflow:hidden;
background: pink;
}


.left {
width: 150px;
margin-right: 10px;
background: yellow;
float:left;
vertical-align: middle;
display:inline-block


}


.left2 {
width: 150px;
margin-right: 10px;
background: aqua;
float:left;
vertical-align: middle;
display:inline-block
}


.right{
width: 150px;
background: orange;
float:right;
vertical-align: middle;
display:inline-block
}

JSFiddle

140079 次浏览

Edited:

The vertical-align CSS property specifies the vertical alignment of an inline, inline-block or table-cell element.

Read this article for Understanding vertical-align

You need to set line-height.

<div style="border: 1px solid red;">
<span style="font-size: 38px; vertical-align:middle; float:left; line-height: 38px">Hejsan</span>
<span style="font-size: 13px; vertical-align:middle; float:right; line-height: 38px">svejsan</span>
<div style="clear: both;"></div>

http://jsfiddle.net/VBR5J/

Vertical alignment doesn't work with floated elements, indeed. That's because float lifts the element from the normal flow of the document. You might want to use other vertical aligning techniques, like the ones based on transform, display: table, absolute positioning, line-height, js (last resort maybe) or even the plain old html table (maybe the first choice if the content is actually tabular). You'll find that there's a heated debate on this issue.

However, this is how you can vertically align YOUR 3 divs:

.wrap{
width: 500px;
overflow:hidden;
background: pink;
}


.left {
width: 150px;
margin-right: 10px;
background: yellow;
display:inline-block;
vertical-align: middle;
}


.left2 {
width: 150px;
margin-right: 10px;
background: aqua;
display:inline-block;
vertical-align: middle;
}


.right{
width: 150px;
background: orange;
display:inline-block;
vertical-align: middle;
}

Not sure why you needed both fixed width, display: inline-block and floating.