我有一个特定的 div
类,它在左上角包含一个图标作为背景图像,在 div
的其余部分包含文本。 div
的最小高度为 32px,以便显示所有图标。
当有多行文本时,这些行看起来很好,因为它们将 div
向下拉伸(stretch)超过最小高度,但当只有一行时,它不会与中心垂直对齐图标。
有没有办法让单行垂直对齐,但在多行时又不会弄乱?
.test {
background-color: #98c5ff;
color: #093d80;
width: 400px;
min-height: 32px;
background-image: url("http://google.com/favicon.ico");
background-repeat: no-repeat;
padding-left: 42px;
}
<div class="test"><p>Short message</p></div>
<hr />
<div class="test"><p>Rather long message that should hopefully wrap on to a second line at some point.</p></div>
<hr />
<div class="test"><p>Message<br />with<br />many<br />lines<br />.</p></div>
最佳答案
您可以像这样在 CSS 中使用 display
:
.test {
background-color: #999999;
display: table; /* Add this in here. */
width: 400px;
min-height: 32px;
background-image: url("http://google.com/favicon.ico");
background-repeat: no-repeat;
padding-left: 42px;
}
.test p {
display: table-cell;
vertical-align: middle;
}
关于html - 在最小高度 div 内垂直对齐单行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15801600/