我是 HTML/CSS 新手,侧边栏中元素的垂直对齐让我抓狂。基本上,我有一个包含文本和图像混合的 div
,我想做的就是垂直对齐 ediv 中间的元素。
根据 this post :
Inline elements (and only inline elements) can be vertically aligned in their context via vertical-align: middle. However, the “context” isn’t the whole parent container height, it’s the height of the text line they’re in.
因此,我创建了一个 SPAN
并设置了 diplay: inline
事件,但没有任何效果:
<div id="main_section" class="main_align" >
<span class="inline">
<span class="inline"><img src="http://placehold.it/50x50" /></span>
<span class="small inline">A Very Small Text</span>
<span class="medium inline">Medium String</span>
</span>
</div>
这是 jsfiddle .
任何指点将不胜感激。
注意:如果这在 Chrome 和 Firefox 中有效,我很高兴。无需解决 IE 的特定问题。
最佳答案
2018 年编辑:我倾向于使用 Flexbox现在很多人都以任何方向为中心。 inline-block 仍然很好,但是 Flexbox 非常强大 :)
如果您还想垂直对齐不同大小的文本(而不是通过它们的基线),那么下面的 fiddle 是一个可能的解决方案,使用 inline-block
:http://jsfiddle.net/vGKjj/13/
HTML:
<div id="main_section" class="main_align" >
<span>
<span class="vam"><img src="http://placehold.it/50x50" /></span>
<span class="small vam">A Very Small Text</span>
<span class="medium vam">Medium String</span>
</span>
</div>
CSS:
.vam {
vertical-align: middle;
}
span.vam {
display: inline-block;
}
.vam img {
vertical-align: top; /* removes a white gap below image */
}
关于html - 如何垂直对齐div中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16486933/