中心文本在div? [英] Center text in div?
问题描述
我有 div
30px
高和 500px
宽。这个 div
可以包含两行文本,一个在另一个之下,并且相应地被样式化(填充)。但有时它只包含一行,我希望它居中。这是可能吗?
I have a div
30px
high and 500px
wide. This div
can contain two lines of text one under the other, and is styled (padded) accordingly. But sometimes it only contains one line, and I want it to be centered. Is this possible?
推荐答案
使用 text-align:center
。
如果在同一行中有另一个元素,垂直居中只能使用 vertical-align:middle
请参阅这里。
To center vertically, one can only use vertical-align:middle
if there is another element in the same row that it is being aligned to.
See it working here.
我们使用高度为100%的空白区域,然后将内容放在下一个垂直对齐的中间元素中。
We use an empty span with a height of 100%, and then put the content in the next element with a vertical-align:middle.
还有其他技术,如使用table-cell或将内容放在绝对定位的元素中,顶部,底部,左侧和右侧都设置为零,但是它们都会受到跨浏览器兼容性问题的影响。
There are other techniques such as using table-cell or putting the content in an absolutely positioned element with top, bottom, left, and right all set to zero, but they all suffer from cross browser compatibility issues.
祝你好运。
这篇关于中心文本在div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!