垂直对齐div元素中的文本

Tom*_*Tom 13 html css vertical-alignment

我知道这个问题已被要求死亡,但通过搜索没有任何东西对我有用.

你知道这个交易,我有一个div元素,我需要垂直对齐文本,但没有任何工作(位置:绝对;顶部:50%; margin-top:-x;显示:table-cell; vertical-align:middle等等)

这是我正在使用的内容(抱歉内联CSS).无论如何,我会使用行高,但文本可以是一行或两行.它应与图像垂直对齐,图像总是最大高度为30px(30x50).

 <div style="margin:0 0 10px 0;padding:10px;border:2px solid #606060;background-color:#2b2b2b;-webkit-border-radius:8px;-moz-border-radius:8px;border-radius:8px;">
 <div style="float:left;width:55px;height:40px;">
 <a href="link"><img style="max-width:50px;border:1px solid #ffb92c;" src="image.jpg" alt="" /></a>
 </div>
 <div style="float:right;width:155px;font-size:0.7em;height:40px;">
 <a href="link">This is the text to vertically align</a>
 </div>
 </div>
Run Code Online (Sandbox Code Playgroud)

bre*_*njt 9

还有一件事你可以做.如果div中只有一行文本可以使用line-height

div {
    line-height:40px;
}
Run Code Online (Sandbox Code Playgroud)


Yiğ*_*ner 8

这个想法来自这里,应该适用于所有浏览器.

<div style="margin: 0 0 10px 0; padding: 10px; border: 2px solid #606060; background-color: #2b2b2b;
    -webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius: 8px;">
    <div style="float: left; width: 55px; height: 40px;">
        <a href="link">
            <img style="max-width: 50px; border: 1px solid #ffb92c;" src="image.jpg"
                alt="" /></a>
    </div>
    <div style="float: right; width: 155px; font-size: 0.7em; height: 40px; display: table; #position: relative; overflow: hidden;">
        <div style="#position: absolute; #top: 50%; display: table-cell; vertical-align: middle;">
            <div style="#position: relative; #top: -50%;">
                <a href="link">This is the text to vertically align</a>
            </div>
        </div>
    </div>
    <div style="clear: both"></div>
</div>
Run Code Online (Sandbox Code Playgroud)