CSS 将文本垂直对齐到框的底部?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10760088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vertically align text to the bottom of the box?
提问by phoxd
I made box and I set line-height, the text is automatically vertically center. Is there a way or any kind of trick to set the text on the bottom of the box?
我制作了框并设置了行高,文本自动垂直居中。有没有办法或任何技巧来设置框底部的文本?
div {
width: 100px;
height: 100px;
background: #eee;
color: #333;
text-align: center;
line-height: 100px;
vertical-align: text-bottom;
}
<div>FoxRox</div>
回答by Ana
2020 Update
2020 更新
You can use CSS grid, flexbox or the original method with line-height:
您可以使用 CSS grid、flexbox 或原始方法line-height:
body { display: flex } /* just to prettify */
div {
margin: .5em;
width: 6.25em; height: 6.25em;
background: #eee;
color: #333;
text-align: center
}
.grid {
display: grid;
align-content: end;
}
.flex {
display: flex;
align-items: flex-end;
justify-content: center
}
.lh { line-height: 11.5 /* 6.25*2 - 1.5 */ }
<div class='grid'>Hello</div>
<div class='flex'>Hello</div>
<div class='lh'>Hello</div>
Setting the heightof the divand the line-heightof the text to the same value, 100pxin your case, is a method of vertically centering the text within the div. That's the problem.
在您的情况下,将文本的heightofdiv和 the设置为line-height相同的值100px是一种将文本垂直居中的方法div。那就是问题所在。
The solution is to change line-heightto twice the height minus the size of the text and remove useless vertical-align.
解决办法是改成line-height两倍高度减去文字大小,去掉无用vertical-align。
回答by xbonez
Enclose the text in a ptag with display:inline-block. Set vertical-alignto the pelement.
用 将文本括在p标签中display:inline-block。设置vertical-align为p元素。
<div>
<p>FoxRox</p>
</div>?
div {
width: 100px;
height: 100px;
background: #eee;
color: #333;
text-align: center;
}
p {
display: inline-block;
vertical-align: -80px;
}
?
回答by walmik
You could set display to table-cell, try this CSS for example.
您可以将显示设置为表格单元格,例如试试这个 CSS。
width: 100px;
height: 100px;
display: table-cell;
vertical-align: bottom;
回答by Code Maverick
You could check out my answer to https://stackoverflow.com/a/6116514/682480.
您可以查看我对https://stackoverflow.com/a/6116514/682480 的回答。
Here is the demofor the above answer.
这是上述答案的演示。
The trick is to use display: table-cellon the outer container. That way you can use the vertical-align: bottomand display: inline-block;on the div.
诀窍是display: table-cell在外容器上使用。这样你就可以在 div 上使用vertical-align: bottom和display: inline-block;。

